我正在使用 Entity Framework 4 和 C#。我有 Contact 对象,这些对象具有 Addresses 的引用实体集合。因此,一个Contact 可以有多个Address 实体。我想要做的是将返回的与 Contact 关联的 Addresses 过滤为仅来自多伦多市。
这是我正在使用的 LINQ 查询,但它会返回所有 Addresses,只要至少有一个具有 City == "Toronto"。我想将返回的 Address 实体限制为仅包含具有 City == "Toronto" 的 Address 实体。我如何构造 LINQ 查询来执行此操作?
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")
};
