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.
Consider the following Linq to Sql entity:
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