简体   繁体   中英

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;
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")
               }; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM