【问题标题】:EF: Can I mix TPH and TPT when abstract base and a few concrete types are in TPH-table and other types have their own table?EF:当抽象基和一些具体类型在TPH-table中并且其他类型有自己的表时,我可以混合使用TPH和TPT吗?
【发布时间】:2011-05-17 17:53:09
【问题描述】:

首先,这些问题相似但绝对不一样:

Can I mix Table per Hierarchy and Table per Type in Entity Framework? - 指不同的场景。

Entity Framework: mix table per type and table per hierarchy - 另一个场景,尽管接受了第一个场景的答案,但与它无关 (*)。

(*) 其次,我在实体框架中成功地混合了每个类型的表和每个层次的表,当使用每个实体的表和具有表的鉴别器的表映射基本实体时 -每个层次结构在链条的下游。


我正在尝试映射以下内容:

表格:

BaseTable
{
    int PK1;
    int PK2;
    string? Value1;
    double? Value2;
}

ChildTable3
{
    int PK1;
    int PK2;
    int Value;
}

实体:

abstract BaseEntity : class // Maps to BaseTable
{
    int PK1; // Maps to PK1 in relevant table
    int PK2; // Maps to PK2 in relevant table
}

Entity1 : BaseEntity // Maps to BaseTable when Value1 != null
{
    string Value; // Maps to Value1
}

Entity2 : BaseEntity // Maps to BaseTable when Value1 == null && Value2 != null
{
    double Value; // Maps to value2
}

Entity3 : BaseEntity // Maps to ChildTable3
{
    int Value; // Maps to value
}

在添加 Entity3 映射之前有效。

添加 Entity3 及其映射后,我在编译时收到以下错误:

错误 1 ​​错误 3026:从第 980、986、995 行开始的映射片段出现问题:表 BaseTable 中可能存在数据丢失或键约束违规。 在以下情况下,具有密钥 (PK) 的实体将不会往返: (PK 在 'BaseTables' EntitySet 中并且实体是类型 [MyNamespace.Entity3]) 路径\到\My.edmx 981 15 我的程序集

  • 有没有办法让这个工作?
  • 如果可以破解 edmx 来完成这项工作,我是否会在每次更新数据库时都放弃破解?

【问题讨论】:

    标签: entity-framework entity-framework-4 table-per-hierarchy table-per-type


    【解决方案1】:

    我找到了一个可以通过设计器执行此类映射的工作流程:

    1. 创建 BaseEntity、Entity1、Entity2、Entity3
    2. 将 BaseEntity 作为抽象映射到 BaseTable
    3. 根据条件将 Entity1 映射到 BaseTable
    4. 根据条件将 Entity2 映射到 BaseTable
    5. 将 Entity3 映射到 ChildTable3
    6. 取消映射 BaseEntity

    稍后添加其他子表:

    1. 重新映射 BaseEntity
    2. 映射新的子表
    3. 取消映射 BaseEntity

    【讨论】:

    • 谢谢!如果可能的话,我宁愿避免使用设计器;有没有办法先在代码中做到这一点?
    • 我上次尝试使用 EF 4.0 进行这种类型的映射(首先是预编码)。
    猜你喜欢
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-25
    • 1970-01-01
    相关资源
    最近更新 更多