使用Entity Framework 4如何过滤引用的实体集合

use*_*673 1 c# linq entity-framework entity-framework-4

我正在使用带有C#的Entity Framework 4。我的Contact对象具有的引用的Entity集合Addresses。因此,一个人Contact可以拥有多个Address实体。我想做的是过滤Addresses与a相关的返回值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;
Run Code Online (Sandbox Code Playgroud)

dev*_*xer 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")
               }; 
Run Code Online (Sandbox Code Playgroud)