我想获取其父为 null 的所有模块,这意味着所有根模块。
此外,我希望每个模块都知道它是否有孩子。
我需要这个功能,因为根模块显示在延迟加载的模块树中。
这样它对 SQL 的工作很快:
SELECT
Id,
CASE WHEN EXISTS (SELECT NULL FROM Module m2 WHERE m2.ParentId = module.Id) THEN 1
ELSE 0
END AS HasChildren
FROM Module
WHERE ParentId IS NULL
如何使用 EF 5 做同样的事情?
更新
这些是我的类,它们是我的 Poco 首先使用 EF 代码:
public class Module
{
public Module()
{
Children = new List<Module>();
}
// PK
public int ModuleId { get; set; }
public string Name { get; set; }
public List<Module> Children { get; set; }
// FK
public int MachineId { get; set; }
public Machine Machine { get; set; }
}
public class Machine
{
// PK
public int MachineId { get; set; }
public string Name { get; set; }
}
更新2
@Gert
这是 EF 为您生成的 sql 解决方案 .Any() 代码:
{SELECT
[Extent1].[ModuleId] AS [ModuleId],
[Extent1].[Name] AS [Name],
CASE WHEN ( EXISTS (SELECT
1 AS [C1]
FROM [dbo].[Module] AS [Extent2]
WHERE [Extent1].[ModuleId] = [Extent2].[Module_ModuleId]
)) THEN cast(1 as bit) WHEN ( NOT EXISTS (SELECT
1 AS [C1]
FROM [dbo].[Module] AS [Extent3]
WHERE [Extent1].[ModuleId] = [Extent3].[Module_ModuleId]
)) THEN cast(0 as bit) END AS [C1]
FROM [dbo].[Module] AS [Extent1]
WHERE ([Extent1].[ParentId] IS NULL) AND ([Extent1].[MachineId] = @p__linq__0)}
您的 linq 查询永远不会为 HasChildren 属性返回 TRUE,因为我以前的查询看起来不同:
context.Modules.SqlQuery("SELECT Module.ModuleId, Module.Name, case when Exists(select null from Module m where m.ParentID = Module.ModuleId) " +
"then 1 else 0 end as HasChildren FROM Module WHERE Module.ParentId Is Null AND Module.MachineId = @MachineId ORDER BY HierarchyIndex",
new SqlParameter("MachineId",machineId)).ToList();
在 EF 生成的“你的”sql 语句中,我错过了重要的 m.ParentId = Module.ModuleId 比较。你做 Extend1.ModuleId = Extend2.Module_ModuleId。
好像有什么不对劲。