How to return both parent and child using LINQ against 1 table

前端 未结 7 723
隐瞒了意图╮
隐瞒了意图╮ 2021-01-19 17:10

Been looking for a solution for this but haven\'t been able to find one so far.

I\'m fairly sure its possible with one linq call but having trouble working it out.

相关标签:
7条回答
  • 2021-01-19 18:10

    Consider the following Linq to Sql entity:

    enter image description here

    Suppose we've named the sides of the OneToMany relationship like ChildTables and ParentTables, then the following code should do the job

    //create data context
    MyTableDataContext dc = new MyTableDataContext("Your connection string"); 
    //find all children, i.e. the entities with ParentId set
    var allChildEntities = dc.MyTable.Where(t=>t.ParentId.HasValue);
    //find all valid parents, which have no parent and no children
    var allParentsWithChild = dc.MyTable.Where(c => !c.ParentId.HasValue && 
                                                    !c.ChildTables.Any());
    //union the results
    var result = allChildEntities.Union(allParentsWithChild);
    

    If there is a foreign key relationship between Id and ParentId, then it's enough. If not, you should also probably search for child entites, with not existing parents. But this would probably be much easier done with pure sql

    0 讨论(0)
提交回复
热议问题