首页 文章

实体框架6 Code First Fluent API表映射

提问于
浏览
1

我在现有数据库中有一个表,如下所示:

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-in-an-asp-net-mvc-application

但它并没有真正谈论使用流畅的api配置类型,而是直接通过 DbSet<> 将它们添加到上下文中 .

如何使用流畅的api设置单个表通过基类映射到不同的类?

1 回答

  • 1

    我转向很多的一个很好的参考是这篇MSDN文章:Configuring/Mapping Properties and Types with the Fluent API

    在其中,您将看到对Table-Per-Layer(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 .

相关问题