【发布时间】:2016-11-16 15:00:16
【问题描述】:
总结:在 Entity Framework 中,我使用 TPC 创建了两个派生自同一个基类的类。在fluent API中我映射继承的属性,但是如何对基类的属性进行建模?
更广泛的描述 在实体框架中,我有一个类 Child 和两种孩子:一个男孩和一个女孩。 Boy 和 Girl 都派生自 Child:
public class Child
{
public int Id {get; set;}
public string Name {get; set;}
}
public class Boy : Child
{
public string SomeBoyishProperty {get; set;}
}
public class Girl : Child
{
public string SomeGirlyProperty {get; set;}
}
我想要一张有男孩的桌子和一张有女孩的桌子,每张桌子也有 Child 属性。
public class MyDbContext : DbContext
{
public DbSet<Boy> Boys {get; set;}
public DbSet<Girl> Girls {get; set;
}
From several sources, for example this one 我知道这叫做 TPC: table per specific class,我应该在 OnModelCreating 中 MapInheritedProperties
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// model the properties of the base class, for instance set max length
modelBuilder.Entity<Child>()
.Property(p => p.Name).IsRequired().HasMaxLength(12);
// Model Daughter:
modelBuilder.Entity<Daughter>()
.Map(m =>
{
m.MapInheritedProperties();
m.ToTable("Daughters");
})
.Property(p => p.SomeGirlyProperty).IsOptional().HasMaxLength(13);
// model Boy
modelBuilder.Entity<Son>()
.Map(m =>
{
m.MapInheritedProperties();
m.ToTable("Sons");
})
.Property(p => p.SomeBoyishProperty).IsOptional().HasMaxLength(14);
}
在 SaveChanges 期间,我收到一个 InvlidOperationException 指示主键不是唯一的。删除构建 Child 的部分可以解决此问题。
如何构建 Child 属性而不必在 Girl 和 Boy 属性中执行此操作?
【问题讨论】:
-
你的
Child类是你真实模型中的抽象吗? -
Child 摘要:我不打算创建 Child 对象,只创建 Boys 和 Girls。我也不想创建子表。因此,如果我可以帮助使 Child 抽象化,那么我会这样做。我当然可以让一个男孩成为一个孩子的组合,这样可以解决问题,但对我来说,男孩有一个孩子而不是一个孩子对我来说似乎有点奇怪
标签: c# entity-framework inheritance ef-fluent-api