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


You can drag and drop it and wrap the delete in try-catch. As long as all deletions are part of the same context, if one of them cannot be deleted due to an FK relationship, it will rollback all deletions in that block.



+1


source


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







All Articles