In Linq, check child relationships?
Is there a way in Linq to check if a parent entry exists in its children?
I have a table that has a foreign key relationship with 12 other tables. All I want to do is see if any records in those child tables are dependent on the parent, so I can delete it without throwing FK constraint errors.
Thanks guys.
I ended up just making an extension class that tested each one ... Lots of time but it did the job ... I still like the opinions if possible
+1
source to share
2 answers
It might be a bit cludgy and you will have to iterate over your child tables and concatenate them all, but here's a start ...
ParentChildrenDataContext context = new ParentChildrenDataContext();
var child1Ids = from c in context.ChildType1s
select c.ParentId;
var child2Ids = from c in context.ChildType2s
select c.ParentId;
var allChildren = child1Ids.Union(child2Ids);
var myParents = from p in context.Parents
where allChildren.Contains<int?>(p.ParentId)
select p;
return myParents.Count();
0
source to share