【问题标题】:EF automatic type per table mapping strategy每个表映射策略的 EF 自动类型
【发布时间】:2014-10-15 01:15:10
【问题描述】:

我们有一个名为 Base 的基类,以及几个名为 Derived1 和 Derived2 的继承类。要将类放在单独的表格中,我们可以使用属性或 fluentAPI,但在这种情况下,我们在定义新类时一直在编写,但新继承的类很常见。

最后,所有与base的后继者的工作都必须经过LolContext的Bases。

那么,是否可以让 EF 将所有继承自 Base 的类自动映射到相应的表中?

public class OneContext : DbContext
{
    public DbSet<Base> Bases { get; set; }

    public OneContext()
        : base("OneDatabase")
    {

    }
}

public class Base
{
    [Key]
    public int Id { get; set; }

    public int prop1 { get; set; }
}

public class Derived1 : Base
{
    public int prop { get; set; }
}

public class Derived2 : Base
{
    public int prop { get; set; }
}

#Update1

我会澄清我的问题。

是否有任何方法可以将所有“Base”继承类放在名为 tabels(或某种名称或 id)的名称中,而不为每个新的后继者指定 [Table("")] 属性并为每个新的后继者定义新的 DbSet OneContext 中的每个新继任者?

【问题讨论】:

    标签: c# entity-framework


    【解决方案1】:

    无法将 EF 配置为自动使用 TPT 而不是 TPH。然而,实现 TPT 的唯一要求是显式设置派生实体类的表名(这可以像在类定义中使用 TableAttribute 一样简单)。为派生实体类创建DbSet&lt;T&gt; 属性是可选的。

    【讨论】:

    • 答案是一样的——你不能避免明确指定 TPT 继承表的名称(这是唯一的配置差异 b/t TPT 和 TPH)。您不需要为每个 TPT 实体创建 DbSet 属性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-03
    • 2018-12-28
    • 2014-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-09
    相关资源
    最近更新 更多