繁体   English   中英

实体框架6代码优先Fluent API表映射

[英]Entity Framework 6 Code First Fluent API Table Mapping

我在现有数据库中有一个表,看起来像这样:

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净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知道要实现的实体类型,即当Type == "Course"时的实体Course

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM