问题
I'm having an odd issue with EF 4.1 Code First where even though I have configured an entity to generate columns for its inherited properties, it still joins to the inherited type's table.
Here are my classes:
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());
}
}
Here is the resulting query:
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]
I only want it to query the Humans table.
回答1:
That is how EF behaves. If you query Human
set it always goes over all derived tables as well because SuperHuman
is still Human
and because of that instances of SuperHuman
are valid results of query for humans.
来源:https://stackoverflow.com/questions/6498532/ef-code-first-retrieving-a-base-type-queries-all-derived-type-tables