使用Entity Framework 4如何过滤引用的Entity Collection

时间:2012-07-31 23:07:14

标签: c# linq entity-framework entity-framework-4

我正在使用带有C#的Entity Framework 4。我有Contact个对象,其引用的实体集合为Addresses。因此,一个Contact可以拥有多个Address实体。我想要做的是将与Addresses相关联的返回Contact过滤为仅来自多伦多市。

这是我正在使用的LINQ查询,但只要至少有一个Addresses,它就会返回所有City == "Toronto"。我想限制返回的Address个实体只包含Address个实体City == "Toronto"。如何构建LINQ查询来执行此操作?

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

1 个答案:

答案 0 :(得分:5)

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