我在使用EF 4.1 Code First时遇到了一个奇怪的问题,即使我已经配置了一个实体来为其继承的属性生成列,它仍然会加入到继承类型的表中。
以下是我的课程:
public class Human
{
public int Id { get; set; }
public string Name { get; set; }
}
public class SuperHuman : Human
{
public int Id { get; set; }
public string Powers { get; set; }
}
public class MarvelDbContext : DbContext
{
public DbSet<Human> Humans { get; set; }
public DbSet<SuperHuman> SuperHumans { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<SuperHuman>().Map(m => m.MapInheritedProperties());
}
}
以下是生成的查询:
SELECT
[Limit1].[C3] AS [C1],
[Limit1].[C1] AS [C2],
[Limit1].[C2] AS [C3],
[Limit1].[C4] AS [C4]
FROM ( SELECT TOP (1)
[UnionAll1].[Id] AS [C1],
[UnionAll1].[Name] AS [C2],
CASE WHEN ([UnionAll1].[C2] = 1) THEN '0X' ELSE '0X0X' END AS [C3],
CASE WHEN ([UnionAll1].[C2] = 1) THEN CAST(NULL AS varchar(1)) ELSE [UnionAll1].[C1] END AS [C4]
FROM (SELECT
[Extent1].[Id] AS [Id],
[Extent1].[Name] AS [Name],
CAST(NULL AS varchar(1)) AS [C1],
cast(1 as bit) AS [C2]
FROM [dbo].[Humen] AS [Extent1]
UNION ALL
SELECT
[Extent2].[Id] AS [Id],
[Extent2].[Name] AS [Name],
[Extent2].[Powers] AS [Powers],
cast(0 as bit) AS [C1]
FROM [dbo].[SuperHumans] AS [Extent2]) AS [UnionAll1]
) AS [Limit1]
我只想查询人类表。
答案 0 :(得分:1)
这就是EF的表现方式。如果您查询Human
设置,它始终会覆盖所有派生表,因为SuperHuman
仍然是Human
,因为SuperHuman
的实例是人类查询的有效结果。