Arnet11
Arnet11

Reputation: 79

Getting many to many relation data in EF

I am new to Entity framework, struggling to get it right. I have sql server three tables,

I am using database first approach and Entity Framework 5. Generated DbContext has only 2 class (mapping table does not have corresponding class).

Parent Class has ICollection<Child> and Child Class has ICollection<Parent>.

I want to get list of child object, based on parent id, if I use

context.Parent
       .Include(f => f.Child)   
       .FirstOrDefault(f => f.ParentId == RequiredParentId)

where RequiredParentId is my filter. This gives me parent object, however I want to retrive only list of childs in Parent. If I change this to

context.Parent
       .Include(f => f.Child)   
       .FirstOrDefault(f => f.ParentId == RequiredParentId)
       .Child

Then If parent is not in database, than ".Child" will throw exception. Also I dont want to load any data for parent, I am just interested in getting list of child based on parent Id.

I also tried writing it another way

   context.Child
         .Include(f => f.Parent)
         .Select(f => f.Parent.FirstOrDefault().ParentId == RequiredParentId);

Here again .Select(f => f.Parent.FirstOrDefault().ParentId will throw exception if there is no child for parent.

Upvotes: 1

Views: 641

Answers (1)

Vlad274
Vlad274

Reputation: 6854

Have you tried the following?

context.Parent.Where(e => e.ParentId == RequiredParentId).SelectMany(e => e.Child)

If the Parent doesn't exist or if no children exist, the resulting collection will be empty.

NOTE: If there are multiple Parents with the same ID this will join the Children of each (with duplicates). I'm assuming that ParentId is the Key for Parent, and thus will not have duplicates

Upvotes: 4

Related Questions