我正在使用带有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;
答案 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")
};