標籤:
首先需要分析業務,提取項目需要的概念性模型,將其用代碼錶示。
基本類型,枚舉類型,複雜類型,以及它們之間的關係,繼承,彙總,組合等方式。
枚舉類型在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; } View Code
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); } }View Code
Entity Framework Code First