确定记录是否在LINQ to SQL中具有子级 [英] Determine if record has children in LINQ to SQL
问题描述
我在具有结构的分层表中ID、名称、FK_ID、排序键
I am having at hierarchical table with the structure ID, Name, FK_ID, Sortkey
直接在LINQ to SQL中获取数据:
Fetching the data in LINQ to SQL is straight forward:
var list = from ls in db.myTable
where ls.FK_ID == levelId
orderby ls.sortkey ascending
select ls;
我可以通过链接到下一个levelId遍历树.
And I can traverse down the tree by linking to the next levelId.
但是我不知道,如果LINQ中有一种方法可以检查是否有任何孩子
But what I can't figure out, if there is a way in LINQ, to check if there is any children
我可能可以构建一个视图,在每个记录中添加一个标志,但是如果可能的话,我宁愿在LINQ中这样做.
I could probably build a view, that added a flag to each record, but I would rather do this in LINQ, if possible.
在SQL中添加此类标志的最佳实践甚至是什么?
What would even be the best practice for adding such a flag in SQL?
我检查每条记录的想法不是最性能友好的解决方案.
My idea on checking each record, is not the most performance friendly solution.
推荐答案
如果正确设置了外键,是否不应该具有一对多"映射属性?
If you have set up the foreign key correctly, should you not have the 1 to Many mapping properties?
即你可以写
var listWithChildren = list.Where(l => l.Children.Any());
或朝另一个方向
var listWithParent = list.Where(l => l.FK_ID != null);
或使用查询表达式代替流利的
or using the query expression instead of fluent
var listWithChildren = from item in list
where item.Children.Any()
select item;
正如您在评论中要求输入布尔标志一样,您可以这样做
as you asked in your comments for a boolean flag, you could do
var updatedList = from item in list
select new
{
Item = item,
HasChildren = item.Children.Any()
};
这篇关于确定记录是否在LINQ to SQL中具有子级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!