I'd like to select only child below CFO
and its subchild entities in an Entity Framework select statement.
Here's my table:
+-------+------------+----------+
| OrgId | Name | ParentId |
+-------+------------+----------+
| 1 | COO | |
+-------+------------+----------+
| 2 | CFO | |
+-------+------------+----------+
| 3 | Accountant | 2 |
+-------+------------+----------+
| 4 | Bookkeeper | 3 |
+-------+------------+----------+
| 5 | Controller | 2 |
+-------+------------+----------+
| 6 | Operations | 1 |
+-------+------------+----------+
I'd like to select only this:
+-------+------------+----------+
| OrgId | Name | ParentId |
+-------+------------+----------+
| 3 | Accountant | 2 |
+-------+------------+----------+
| 4 | Bookkeeper | 3 |
+-------+------------+----------+
| 5 | Controller | 2 |
+-------+------------+----------+
The entity framework select:
public virtual IList<OrgStructureModel> GetAll()
{
using (var db = _context)
{
var result = _session.GetObjectFromJson<IList<OrgStructureModel>>("OrgStructure");
if (result == null)
{
result = db.OrgStructures
.Select(org => org.ToOrgStructureModel(db.OrgStructures.Where(s => s.ParentId == org.OrgId).Count() > 0))
.ToList();
_session.SetObjectAsJson("OrgStructure", result);
}
return result;
}
}
How can this be achieved in EF?
Here's what I've tried
I've tried testing to just show child with any parent .Where(e => e.ParentId != null)
:
result = db.OrgStructures
.Select(org => org.ToOrgStructureModel(db.OrgStructures.Where(s => s.ParentId == org.OrgId).Count() > 0))
.Where(e => e.ParentId != null)
.ToList();
But this returned 0 results
Definition of ToOrgStructureModel
:
public static OrgStructureModel ToOrgStructureModel(this OrgStructure org, bool hasChildren)
{
return new OrgStructureModel
{
OrgId = org.OrgId,
ParentId = org.ParentId,
Name = org.Name
hasChildren = hasChildren
};
}
Update:
It looks like something's wrong with the Telerik TreeList Control where the above query has data, but the control won't output the data. But the question remains, how do I get OrgId: 3,4,5
with LINQ?