Reputation: 10153
Is there any way in Linq to check to see if a record of a parent 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 depend on the parent, so I can delete it without causing errors with FK constraints.
Thanks guys.
I ended up just making an extension class that checked each one... Time consuming but got the job done... I would still like opinions if possible
Upvotes: 1
Views: 725
Reputation: 12609
You could brute-force it and wrap the delete in a try-catch. As long as all the deletes are part of the same context, if one child can't be deleted due to a FK relationship, it will roll back all the deletes in that block.
Upvotes: 1
Reputation: 5236
This may be kinda cludgy, and you would have to loop through your child tables and union 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();
Upvotes: 0