我只想在Entity Framework select语句中选择CFO
以下的子项及其子子项。
这是我的桌子:
+-------+------------+----------+
| OrgId | Name | ParentId |
+-------+------------+----------+
| 1 | COO | |
+-------+------------+----------+
| 2 | CFO | |
+-------+------------+----------+
| 3 | Accountant | 2 |
+-------+------------+----------+
| 4 | Bookkeeper | 3 |
+-------+------------+----------+
| 5 | Controller | 2 |
+-------+------------+----------+
| 6 | Operations | 1 |
+-------+------------+----------+
我只想选择一个:
+-------+------------+----------+
| OrgId | Name | ParentId |
+-------+------------+----------+
| 3 | Accountant | 2 |
+-------+------------+----------+
| 4 | Bookkeeper | 3 |
+-------+------------+----------+
| 5 | Controller | 2 |
+-------+------------+----------+
实体框架选择:
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;
}
}
这在EF中如何实现?
这是我尝试过的
我已经尝试过测试,以显示与任何父母.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();
但这返回了0条结果
ToOrgStructureModel
的定义:
public static OrgStructureModel ToOrgStructureModel(this OrgStructure org, bool hasChildren)
{
return new OrgStructureModel
{
OrgId = org.OrgId,
ParentId = org.ParentId,
Name = org.Name
hasChildren = hasChildren
};
}
更新:
Telerik TreeList控件似乎有问题,其中上面的查询中有数据,但该控件不会输出数据。但是问题仍然存在,我如何使用LINQ获得OrgId: 3,4,5
?
答案 0 :(得分:-1)
仅在ParentId不为null的情况下返回结果。