1.前言
Code First是Entity Framework提供的一种新的编程模型。通过Code First我们可以在还没有建立数据库的情况下就开始编码,然后通过代码对象来生成数据库。当然我们在实际开发过程当中要做单元测试。进而每次测试的时候 要对库进行初始化,这样就不会因上次测试而对本次测试有所影响。下面是具体的实现。
2.建立对象
2.1建立对象
/// <summary> /// model对象 /// </summary> public class model_item : supermodel { public model_item() { type = ItemType.Normal;//枚举类型初始化 } [Required] [StringLength(16, MinimumLength = 2)] public string name { get; set; } [Required] [StringLength(16, MinimumLength = 2)] public string code { get; set; } public ItemType type { get; set; } public bool State { get; set; } public string Icon { get; set; } public long sort { get; set; } public long appid { get; set; } }
2.2.DBContext
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>(); } }
2.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.model_item.Add(o));
context.SaveChanges();
}
}
3.EF Code First
3.1新增
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} ", item2.PropertyName, item2.ErrorMessage)); } } Console.WriteLine("数据库初始化报错:" + error); throw ex; } catch (Exception e) { Console.WriteLine("数据库初始化报错:" + e.Message); throw e; } }
3.2移除
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(); } }
3.3初始化
public bool Rebuild() { return Remove() && Build(); }