时间:2021-07-01 10:21:17 帮助过:3人阅读
public class DataInit : IDataInitializer<GDG_DbContext>
{
public void Initialize(GDG_DbContext context) { List<model_item> fim = new List<model_item>() { new model_item(){name="郭德纲",code="gdg",type= ItemType.Normal,State=true,Icon="taoxin.png",sort=0,appid=0,reg_time=DateTime.Now}, new model_item(){name="于谦",code="yq",type= ItemType.Normal,State=true,Icon="juanmao.png",sort=1,appid=1,reg_time=DateTime.Now}, new model_item(){name="德云社",code="dys",type= ItemType.Normal,State=true,Icon="yun.png",sort=2,appid=2,reg_time=DateTime.Now}, }; fim.ForEach(o => context.fee_item.Add(o)); context.SaveChanges(); }
}
public class GDG_DbContext : DbContext { public GDG_DbContext() : base("GDG_DbContext") { } public DbSet<model_item> model_item { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); } }
public bool Build() { try { var context = new FeeDbContext(); if (!context.Database.Exists()) { new List<IDataInitializer<GDG_DbContext>>() { new DataInit() }.Setup<GDG_DbContext>(context); return true; } return false; } catch (DbEntityValidationException ex) { StringBuilder error = new StringBuilder(); foreach (var item in ex.EntityValidationErrors) { foreach (var item2 in item.ValidationErrors) { error.Append(string.Format("{0}:{1}\r\n", item2.PropertyName, item2.ErrorMessage)); } } Console.WriteLine("数据库初始化报错:" + error); throw ex; } catch (Exception e) { Console.WriteLine("数据库初始化报错:" + e.Message); throw e; } }
public bool Remove() { var context = new GDG_DbContext(); try { if (context.Database.Exists()) { return context.Database.Delete(); } return true; } catch (Exception e) { Console.WriteLine("数据库初始化报错:" + e.Message); return false; } finally { context.Dispose(); } }
public bool Rebuild() { return Remove() && Build(); }
code first 创建和初始化数据库
标签: