Mou Mou - 1 month ago 19
C# Question

Entity Framework: How to select nested entity

my entity hierarchy is Customer > Address > Contact. so i use this code to iterate in contact details.

Contacts CurrentContacts = null;

foreach (var existingContacts in existingCustomer.Addresses.Select(a => a.Contacts.Where(cc=> cc.ContactID==5)))
{
CurrentContacts = existingContacts;
}


but this line
CurrentContacts = existingContacts;
throwing error


Cannot implicitly convert type
'System.Collections.Generic.IEnumerable' to
'EFTest.Contacts'. An explicit conversion exists (are you missing a
cast?)


what is my mistake.
existingContacts
will have contacts related data and
CurrentContacts
is a variable of contact type.

so please tell me how could i do it.

Answer

I think you have two problems, but without seeing how the Contacts type is defined it's just a guess.

As @Taemyr points out, you need to use SelectMany instead of Select to flatten the collection of collections.

But unless Contacts is inherited from List<EFTest.Contacts> you still aren't going to be able to do the assignment, you need to change your variable declaration to:

IEnumerable<Contacts> CurrentContacts = null;
Comments