首先需要分析业务,提取项目需要的概念模型,将其用代码表示。
基本类型,枚举类型,复杂类型,以及它们之间的关系,继承,聚合,组合等方式。
枚举类型在Entity Framework 6 中已支持,可直接定义使用
复杂类型可在 使用[ComplexType] 标注在类上,也可在 FluentAPI 定义
继承在映射到数据表,默认是TPH 所有的属性映射到基类表中。
也可使用如下代码将每一个类型映射到一张表上
modelBuilder.Entity<PORequestEntry>().ToTable("PORequestEntrys");
如需将每个子类极其继承属性映射到一张表中,可使用MapInheritedProperties 方法。
modelBuilder.Entity<PORequestEntry>().Map(m => { m.MapInheritedProperties(); m.ToTable("PORequestEntry"); });
将同一类型映射到不同表
modelBuilder.Entity<PORequest>() .Map(m=> { m.Properties(t => new{ t.FBillNo, t.FDate }); m.ToTable(PORequest); }) .Map(m=> { m.Properties(t=> new { t.PoAddress.StreetNumber, t.PoAddress.StreetName }); m.ToTable(PORequestAddress); });
将不同类型映射到同一表
modelBuilder.Entity<PORequestEntry>().ToTable("OtherTable");
之后定义上下文,使用Migrations 将定义的结构映射到资料库中。
如需初始化一些数据,可新增一个继承DropCreateDatabaseAlways 类的方法在上下文构造函数中调用即可
public class DBInitializer : DropCreateDatabaseAlways<ApplicationDbContext> { protected override void Seed(ApplicationDbContext context) { MGFunc mgfun1 = new MGFunc(); mgfun1.Id = "001"; mgfun1.FName = "权限管理"; mgfun1.FUrl = "/Manage/MGFunc/index"; mgfun1.CreatedDate = DateTime.Now; base.Seed(context); } }
public enum POTranType { Office = 1, WearHourse = 2 } public class PORequest : AuditableEntity { [MaxLength(100)] public string FBillNo { set; get; } public DateTime FDate { set; get; } public POTranType FTranType { set; get; } [MaxLength(100)] public string FStatus { set; get; } [MaxLength(200)] public string FNote { set; get; } public Address PoAddress { set; get; } public List<PORequestEntry> PORequestEntrys { set; get; } } [ComplexType] public class Address { [MaxLength(50)] public string StreetNumber { get; set; } [MaxLength(200)] public string StreetName { get; set; } } public class PORequestEntry : AuditableEntity { [MaxLength(100)] public string FInterID { set; get; } [Required] [Range(0, 500)] public decimal FQty { set; get; } public decimal FPrice { set; get; } public decimal FSecQty { set; get; } [MaxLength(100)] public string FItemID { set; get; } [ForeignKey("FItemID")] public ItemCore FItem { set; get; }
public class ApplicationDbContext : DbContext { public DbSet<MGFunc> MGFunc { set; get; } public DbSet<ItemCore> ItemCore { set; get; } public DbSet<PORequest> PORequest { set; get; } public DbSet<PORequestEntry> PORequestEntry { set; get; } public ApplicationDbContext() : base("SeCommerce2") { //Database.SetInitializer<ApplicationDbContext>(new DBInitializer()); } protected override void OnModelCreating(DbModelBuilder modelBuilder) { //modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); //modelBuilder.Conventions.Add<StoreGeneratedIdentityKeyConvention>(); base.OnModelCreating(modelBuilder); } }