我在现有数据库中有一个表,看起来像这样:
PK
FK
Col1
Col2
Col3
Col4
Col5
我需要将其放入这样的类层次结构中:
public abstract class BaseClass : Entity
{
public int PK {get; set;}
public string Col1 {get; set;}
}
public class Child1 : BaseClass
{
public string Col2 {get; set;}
public string Col3 {get; set;}
}
public class Child2 : BaseClass
{
public string Col4 {get; set;}
public string Col5 {get; set;}
}
我目前正在使用Fluent API来配置实体,如下所示:
public abstract class BaseClassConfig<TEntity> : EntityTypeConfiguration<TEntity> where TEntity : Entity
{
public BaseClassConfig()
{
ToTable("TheTableName");
HasKey(x => x.Id);
Property(x => x.Col1).HasColumnName("SomeName");
}
}
public class Child1Config : BaseClassConfig<Child1>
{
public Child1Config()
{
Property(x => x.Col2).HasColumnName("SomeName");
Property(x => x.Col3).HasColumnName("SomeName");
}
}
public class Child2Config : BaseClassConfig<Child2>
{
public Child2Config()
{
Property(x => x.Col4).HasColumnName("SomeName");
Property(x => x.Col5).HasColumnName("SomeName");
}
}
当我将它们添加到上下文中时,继承自DbContext
:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new Child1Config());
modelBuilder.Configurations.Add(new Child2Config());
}
我收到以下错误:
实体类型'Child1'和'Child2'无法共享表'TheTableName',因为它们不在同一类型层次结构中,或者没有有效的一对一外键关系且它们之间具有匹配的主键。
我看了一下这篇文章:http : //www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/implementing-inheritance-with-the-entity-framework-在asp-net-mvc应用程序中
但是,它并没有真正谈论使用fluent api配置类型,而是通过将它们直接添加到上下文中DbSet<>
。
如何使用流利的api设置单个表以通过基类映射到不同的类?
这篇MSDN文章对我有很多帮助:使用Fluent API配置/映射属性和类型
在其中,您将看到对每层表格(TPH)继承模式的引用。本质上,您缺少的是一个鉴别符字段(并且基于该错误,FK也未映射)。
默认情况下,discriminator列称为Discriminator
,但是正如您从本文中看到的那样,可以在代码优先的映射中对其进行自定义:
modelBuilder.Entity<Course>()
.Map<Course>(m => m.Requires("Type").HasValue("Course"))
.Map<OnsiteCourse>(m => m.Requires("Type").HasValue("OnsiteCourse"));
在上面的示例中,Type
是鉴别符,它使EF知道要实现的实体类型,即Course
何时实体Type == "Course"
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句