【发布时间】:2016-04-01 10:35:09
【问题描述】:
假设您有两个从抽象基类派生的实体,并且您希望实现 Table-Per-Concrete-Type。如下实体:
public abstract class EntityBase
{
public int Id { get; set; }
public string CreatedBy { get; set; }
public DateTime CreatedAt { get; set; }
}
public class Person : EntityBase
{
public string Name { get; set; }
}
public class PersonStatus : EntityBase
{
public string Title { get; set; }
}
你不想在抽象基类(EntityBase)中使用属性,你想为所有实体在dbcontext中映射EntityBase类一次。如何更改以下代码:
public class PeopleDbContext : DbContext
{
public DbSet<Person> People { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// Entity base class mapping(only once)
modelBuilder.Entity<Person>(e =>
{
e.Property(x => x.Name)
.IsRequired()
.HasMaxLength(100);
});
modelBuilder.Entity<PersonStatus>(e =>
{
e.Property(x => x.Title)
.IsRequired()
.HasMaxLength(100);
});
}
}
【问题讨论】:
-
你有什么尝试吗?我有这样的设置,并且 Id 是按约定提取的。
-
是的,当我尝试在 dbcontext 中映射(流利)EntityBase 类时,ef 为 EntityBase 类创建了另一个表。在此之前,我使用流利的 nhibernate 实现,并且使用 ClassMap 可以正常工作。另外,我使用了 ef 6 “builder.Types
(..)”。它按我的意愿工作。但是使用 ef core 我做不到。