Mou Mou - 1 year ago 123
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

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

so please tell me how could i do it.

Answer Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download