我希望在我的应用程序中有每种具体类型的表继承:
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操作符?我该怎么解决呢?
发布于 2016-06-26 10:18:37
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类,这样如果使用MapInheritedProperties(),EF就不会尝试使用继承逻辑。
发布于 2016-06-26 08:55:24
关于此主题,堆栈溢出有几个问题。
EF以您所看到的方式工作,如果您请求Base,您将接收实现Base的所有对象(即Base和派生对象)。如果使用TPC,您将看到UNION,如果使用TPH,则会看到EF忽略了区分器字段上的where子句(即,TPC或TPH不重要,结果总是相同的)。GetType不是EF规范函数,所以您不能使用它,但是我已经阅读了关于EF6.x的文章,您可以使用is (在您的例子中是!(m is ExtendedRow))。实际上我不知道它是否有效。
通常,我不映射基类(也就是说,我创建一个从基类派生的空类,而不是映射它)。
https://stackoverflow.com/questions/38036376
复制相似问题