2016-07-25 57 views
0

我是新來的實體framework.I有機會通過使用代碼首先通過谷歌的一些概念接近。當爲自定義列創建映射規則,我發現一個方式OnModelCreating() 工作EF6難道還有比這使其它任何其他方式我們可以用代碼優先的方法在db中創建表。 如果有什麼方法......哪種方法更好?如何在EF6中爲自定義實體創建映射規則?

回答

1

對了,還有其他的方式來映射類和它更好選項。至少,我是這樣的。您可以爲您的模型映射它繼承通用EntityTypeConfiguration並添加此映射OnModelCreating。這樣,如果你有很多模型,你的代碼將保持乾淨並且更容易管理映射。

模型類:

public class Person 
{ 
    public int Id { get; set; } 
    public string FullName { get; set; } 
    public int Age { get; set; } 
} 

映射器類:

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
{ 
    modelBuilder.Configurations.Add(new PersonMap()); 

    base.OnModelCreating(modelBuilder); 
} 

internal class PersonMap 
    : EntityTypeConfiguration<Person> 
{ 
    public PersonMap() 
    { 
     // Primary key 
     this.HasKey(m => m.Id); 

     // Properties 
     this.Property(m => m.FullName) 
      .HasMaxLength(50);  

     // Table & column mappings 
     this.ToTable("TABLE_NAME", "SCHEMA_NAME") 
     this.Property(m => m.Id).HasColumnName("ID"); 
     this.Property(m => m.FullName).HasColumnName("FULL_NAME"); 
     this.Property(m => m.Age).HasColumnName("AGE"); 

     // Relationship mappings 
     // Map your naviagion properties here if you have any. 
    } 
} 

然後你在OnModelCreating方法添加映射