我有一個.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完整的框架代碼