【问题标题】:Entity Framework TPC inheritance issue实体框架 TPC 继承问题
【发布时间】:2016-10-28 10:18:45
【问题描述】:

我想在我的应用程序中使用 Table Per Concrete 类型继承:

public class Row {
    public int Id {get;set;}
    public string Name {get;set;}
}

public class ExtendedRow : Row {
    public int Weight {get;set;}
}

每个类都需要映射到自己的视图,ExtendedRow 视图拥有Row 视图的所有列。

我的配置是:

    modelBuilder.Entity<Row>().Map(m => {
        m.MapInheritedProperties();
        m.ToTable("Row");
    });
    modelBuilder.Entity<ExtendedRow >().Map(m => {
        m.MapInheritedProperties();
        m.ToTable("ExtendedRow");
    });

查询ExtendedRow 就可以了。但是,查询Row 会生成以下 SQL:

SELECT 
        [Extent1].[Id] AS [Id], 
        [Extent1].[Name] AS [Name]
        FROM [dbo].[Row] AS [Extent1]
UNION ALL
SELECT 
        [Extent2].[Id] AS [Id], 
        [Extent2].[Name] AS [Name]
        FROM [dbo].[ExtendedRow] AS [Extent2]

EF 为什么要添加UNION ALL 运算符?我该如何解决?

【问题讨论】:

    标签: sql .net entity-framework inheritance entity-framework-6


    【解决方案1】:

    关于此主题的堆栈溢出有几个问题。
    EF 以您看到的方式工作,如果您要求 Base,您将收到所有实现 Base 的对象(即 Base 和派生对象)。如果您使用 TPC,您将看到 UNION,如果您使用 TPH,您将看到 EF 省略了鉴别器字段上的 where 子句(即 TPC 或 TPH 无关紧要,结果始终相同)。 GetType 不是 EF 规范函数,因此您不能使用它,但我已经读过您可以使用 EF 6.x (在您的情况下为 !(m is ExtendedRow))。其实我不知道它是否有效。

    通常我不映射基类(即,我创建一个从基类派生的空类,而不是映射它)。

    【讨论】:

      【解决方案2】:

      找到了一个对我有用的建议here

      public abstract class RowBase {
          public int Id {get;set;}
          public string Name {get;set;}
      }
      
      public class Row : RowBase {
      }
      
      public class ExtendedRow : RowBase {
          public int Weight {get;set;}
      }
      

      关键是要有一个abstract 类,这样EF 在使用MapInheritedProperties() 时就不会尝试使用继承逻辑。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-23
        • 2016-03-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多