我有三个班级:
public class EntityBase
{
public Guid Id { get; set; }
[MaxLength(50)]
public string Name { get; set; }
public List<Tag> Tags { get; set; }
}
public class Entity : EntityBase
{
[MaxLength(50)]
public string Text { get; set; }
}
public class Entity1 : EntityBase
{
[MaxLength(50)]
public string Text2 { get; set; }
}
如果我查询基本实体并仅投影普通属性(例如,名称) - 一切都很好,派生类不会加入查询,因为不需要它们的信息。
var entities = dataContext.Entities
.Select(e => new { Name = e.Name })
.ToList();
将我的查询转换为:
SELECT
1 AS [C1],
[Extent1].[Name] AS [Name]
FROM [dbo].[EntityHeaders] AS [Extent1]
SELECT
1 AS [C1],
[Extent1].[Name] AS [Name]
FROM [dbo].[EntityHeaders] AS [Extent1]
但是,如果我需要获取基类的集合,则所有派生类的表都会出现在查询中。
var entities = dataContext.Entities
.Include(e => e.Tags)
.Select(e => new { Name = e.Name, Tags = e.Tags })
.ToList();
我有这个
SELECT
[Project1].[Id1] AS [Id],
[Project1].[Id2] AS [Id1],
[Project1].[Id] AS [Id2],
[Project1].[C1] AS [C1],
[Project1].[Name] AS [Name],
[Project1].[C2] AS [C2],
[Project1].[Id3] AS [Id3],
[Project1].[Value] AS [Value],
[Project1].[EntityBase_Id] AS [EntityBase_Id]
FROM ( SELECT
[Extent1].[Id] AS [Id],
[Extent1].[Name] AS [Name],
[Extent2].[Id] AS [Id1],
[Extent3].[Id] AS [Id2],
1 AS [C1],
[Extent4].[Id] AS [Id3],
[Extent4].[Value] AS [Value],
[Extent4].[EntityBase_Id] AS [EntityBase_Id],
CASE WHEN ([Extent4].[Id] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C2]
FROM [dbo].[EntityHeaders] AS [Extent1]
LEFT OUTER JOIN [dbo].[DerivedEntities2] AS [Extent2] ON [Extent1].[Id] = [Extent2].[Id]
LEFT OUTER JOIN [dbo].[DerivedEntities1] AS [Extent3] ON [Extent1].[Id] = [Extent3].[Id]
LEFT OUTER JOIN [dbo].[Tags] AS [Extent4] ON [Extent1].[Id] = [Extent4].[EntityBase_Id]
) AS [Project1]
ORDER BY [Project1].[Id1] ASC, [Project1].[Id2] ASC, [Project1].[Id] ASC, [Project1].[C2] ASC
有可能避免这种情况吗?