【问题标题】:Code first TPC Inheritance with concrete base and derived, concrete types in EFEF 中具有具体基础和派生具体类型的代码优先 TPC 继承
【发布时间】:2011-07-18 12:20:11
【问题描述】:

我正在尝试使用 Code First 设置 TPC 继承来对传入和传出消息以及其中的记录进行建模。 基本类型 SentRecord 是具体的,其派生类型 ReceivedRecord 也是具体的,并且继承自 SentRecord 并添加了一些额外字段以记录返回码。类似这样,但具有更多属性:

public class SentRecord : RecordBase {
    public int Id { get; set; }
    public string FooField { get; set; }
}

public class ReceivedRecord : SentRecord {
    public int ReturnCode { get; set; }
    public SentRecord SentRecord { get; set; }
}

当前模型是 TPH,因此表会获得一个标识符列来标识持久化对象的类型。它可以工作,但我希望两个对象都存储在单独的表中,而不需要鉴别器列。 SentRecord 表将只有 Id 和 FooField 列,而 ReceivedRecord 表将具有 Id、FooField、ReturnCode 和 SentRecord 的 FK。

我的 DataContext 类中目前有以下内容:

public class Context : DContext {
    public DbSet<SentRecord> SentRecords { get; set; }
    public DbSet<ReceivedRecord> ReceivedRecords { get; set; }
}

我对 ReceivedRecord 有以下配置:

public class ReceivedRecord_Configuration : EntityTypeConfiguration<ReceivedRecord>{
    public ReceivedRecord_Configuration() {
        this.Map(m => {
            m.MapInheritedProperties();
            m.ToTable("ReceivedRecords");
        });
    }
}

SentRecord 如下:

public class SentRecord_Configuration : EntityTypeConfiguration<SentRecord>{
    public SentRecord_Configuration() {
        this.Map(m => {
            m.MapInheritedProperties(); //In order to map the properties declared in RecordBase
            m.ToTable("SentRecords");
        });
    }
}

但是一旦我运行它,当 EF 尝试初始化我的数据库时,我会收到以下错误:

Problem in mapping fragments starting at lines 455, 1284:
An entity from one EntitySet is mapped to a row that is also mapped to an entity from another EntitySet with possibly different key.
Ensure these two mapping fragments do not map two unrelated EntitySets to two overlapping groups of rows.

我不知道该怎么做才能按照我上面描述的 TPC 方式进行设置?还是我应该坚持使用有效的 TPH?

提前致谢!

【问题讨论】:

    标签: entity-framework entity-framework-4.1 ef-code-first


    【解决方案1】:

    好的,我已经启动并运行了。说实话,我给出的示例比我正在使用的实际类和继承层次结构要简单一些。该层次结构包含许多抽象类和其他类继承自的具体类。

    通过减少继承来“扁平化”层次结构使其工作顺利且没有任何错误。响应消息不再继承自已发送消息。

    简短版:在尝试使用代码优先数据库模型时,不要使用混合的具体和抽象基类型制作复杂的继承树。它只会让持久化变得更加复杂。

    【讨论】:

      猜你喜欢
      • 2019-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-04
      • 2015-09-01
      • 2017-10-16
      • 1970-01-01
      相关资源
      最近更新 更多