2017-09-19 61 views
2

我有一個.net核心2.0項目,我正在使用實體框架核心2.0 我想映射一個具有繼承的實體,並且此繼承也具有繼承如何映射具有繼承的實體 - 實體框架核心2.0

我的實體,我想在[Domain.Project]映射:

public class Customer : BaseEntity 
{ 
    public Customer(Name name, DateTime? birthDay, Email email, string password, List<CreditDebitCard> creditDebitCards = null) 
    { 
      CreationDate = DateTime.Now; 
      Name = name; 
      BirthDay = birthDay; 
      Email = email; 
      Password = password; 
      _CreditDebitCards = creditDebitCards ?? new List<CreditDebitCard>(); 
    } 

    [Fields...] 
    [Properties...] 
    [Methods...] 
} 

BaseEntity[Domain.Project]

public abstract class BaseEntity : Notifiable 
{ 
    public BaseEntity() 
    { 
      CreationDate = DateTime.Now; 
      IsActive = true; 
    } 

    [Fields...] 
    [Properties...] 
    [Methods...] 
} 

Notifiable[Shared.Project](看,它有Notification類型的列表):

public abstract class Notifiable 
{ 
    private readonly List<Notification> _notifications; 

    protected Notifiable() { _notifications = new List<Notification>(); } 

    public IReadOnlyCollection<Notification> Notifications => _notifications; 
    [Methods...] 
} 

Notification[Shared.Project]

public class Notification 
{ 
    public Notification(string property, string message) 
    { 
     Property = property; 
     Message = message; 
    } 

    public string Property { get; private set; } 
    public string Message { get; private set; } 
} 

我的實體框架上下文類在[Infra.Project]

public class MoFomeDataContext : DbContext 
{ 
    public DbSet<Customer> Customers { get; set; } 

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) 
    { 
     optionsBuilder.UseSqlServer(Runtime.ConnectionString); 
    } 

    protected override void OnModelCreating(ModelBuilder modelBuilder) 
    { 
     modelBuilder.Entity<CreditDebitCard>().Map(); 
    } 
} 

我的Mapping班級[Infra.Project]

public static class CustomerMap 
{ 
    public static EntityTypeBuilder<Customer> Map(this EntityTypeBuilder<Customer> cfg) 
    { 
     cfg.ToTable("Customer"); 
     cfg.HasKey(x => x.Id); 
     cfg.Property(x => x.BirthDay).IsRequired(); 
     cfg.OwnsOne(x => x.Email); 
     cfg.OwnsOne(x => x.Name); 
     cfg.HasMany(x => x.CreditDebitCards); 

     return cfg; 
    } 
} 

當我嘗試添加一個遷移,我得到這個錯誤:

The entity type 'Notification' requires a primary key to be defined.

但是,無論是Notification類,而本Notifiable類在我的背景下已經映射,它們不能被映射。

我做它在.NET完整的框架和它的作品here是.NET完整的框架代碼

回答

3

按照慣例EF核心發現和映射所有屬性實體類和其所有的基類。在你的情況下,Notifications屬性被發現並標識爲集合導航屬性,因此元素類型Notification被映射爲實體。

這是因爲默認的假設是實體模型代表商店模型。表示非商店屬性的成員應該明確地取消映射。要解決此問題,只需添加以下到您的OnModelCreating覆蓋:

modelBuilder.Ignore<Notification>(); 

參考文獻: