user31673
user31673

Reputation: 13685

Using Entity Framework 4 how to filter referenced Entity Collection

I am using the Entity Framework 4 with C#. I have Contact objects that have a referenced Entity collection of Addresses. Therefore, one Contact can have more than one Address entity. What I want to do is filter the returned Addresses associated with a Contact to only be from the city of Toronto.

Here is the LINQ query I am using but it returns all the Addresses as long as at least one has City == "Toronto". I want to limit the Address entities returned to only include the Address entities have City == "Toronto". How can I structure the LINQ query to do this?

var vcontact = from c in context.Contacts
               orderby c.LastName
               where c.Addresses.Any(a => a.City == "Toronto")
               select c;

Upvotes: 1

Views: 576

Answers (1)

devuxer
devuxer

Reputation: 42344

var vcontact = from c in context.Contacts
               orderby c.LastName
               where c.Addresses.Any(a => a.City == "Toronto")
               select new Contact
               {
                   LastName = c.LastName;
                   // map all remaining properties of Contact
                   Addresses = c.Addresses.Where(a => a.City == "Toronto")
               }; 

Upvotes: 5

Related Questions