I want to get all modules whose parent is null that means all root modules.
Furthermore I want that every module knows whether it has children or not.
I need this feature because the root modules are displayed in a lazy loaded module tree.
That way it worked quickly for 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
How can I do the same using EF 5 ?
UPDATE
These are my classes which are my Poco`s using EF code first:
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; }
}
UPDATE 2
@Gert
This is the sql generated by EF for you solution .Any() code:
{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)}
Your linq query never returns TRUE for HasChildren property because my formery query looks different:
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();
In "your" sql statement generated by EF I miss the important m.ParentId = Module.ModuleId compare. You do Extend1.ModuleId = Extend2.Module_ModuleId.
There seems something wrong.