Determine if record has children in LINQ to SQL

天涯浪子 提交于 2021-02-05 08:09:12

问题


I am having at hierarchical table with the structure ID, Name, FK_ID, Sortkey

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;

And I can traverse down the tree by linking to the next levelId.

But what I can't figure out, if there is a way in LINQ, to check if there is any children

I could probably build a view, that added a flag to each record, but I would rather do this in LINQ, if possible.

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.


回答1:


If you have set up the foreign key correctly, should you not have the 1 to Many mapping properties?

i.e. You could write

var listWithChildren = list.Where(l => l.Children.Any());

or going the other direction

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()
                  };


来源:https://stackoverflow.com/questions/18346666/determine-if-record-has-children-in-linq-to-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!