我有一个使用 EF4 连接到 SQL Server 数据库的 asp.net C# 应用程序。
在数据库中我有两个表之间的多对多关系,Officer
和 Geography
- 所以另一个表叫做 OfficerGeography
连接两者的存在。
有了这个用于创建 edmx 图的数据库,EF4 正确地看到了这两个表之间的多对多关系。
问题
我有一个 List<int>
geographyIds,对应于 Geography
的主键表。
我希望使用这个列表来检索具有出现在这个列表中的 geographyId 的军官。我认为以下 LINQ 会起作用:
var geographyIds = new List<int>() { 1, 2, 3, 4, 5 };
var officers = db.Officers.Where(o => o.Enabled == true && geographyIds.Contains(o.Geographies.GeographyId));
但是这失败了。事实上,智能感知不会列出 o.Geographies
的任何列。 (因为多对多的关系)。
如何检索具有 GeographyId 匹配项的官员列表?
补充说明
OfficerGeography
数据库表在 EF4 中不显示为它自己的实体。 EF4 只能正确看到 Officer
和 Geography
,在两个实体上都具有从一个到另一个的导航属性。
最佳答案
怎么样
var officers = db.Officers
.Where(o => o.Enabled == true
&& o.Geographies.Any(g => geographyIds.Contains(g.Id)));
geographyIds.Contains() 接受一个int作为参数,但是每个officer可能有多个geographies,所以要用any-method来一个一个地查。
关于c# - EF4 - 多对多关系,使用 contains 和 List<int> 进行查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5066179/