tags:

views:

270

answers:

2

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

+1  A: 

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.

gfrizzle
A: 

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