c# - EF4 - 多对多关系,使用 contains 和 List<int> 进行查询

标签 c# entity-framework-4 linq-to-entities contains

我有一个使用 EF4 连接到 SQL Server 数据库的 asp.net C# 应用程序。

在数据库中我有两个表之间的多对多关系,OfficerGeography - 所以另一个表叫做 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 只能正确看到 OfficerGeography ,在两个实体上都具有从一个到另一个的导航属性。

最佳答案

怎么样

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/

相关文章:

c# - 构建具有插件支持的应用程序

c# - 创建需要管理员权限的程序/安装包

c# - 在数据库中创建条目会复制传递的变量而不是 FK

entity-framework - Entity Framework 和继承 : NotSupportedException

entity-framework-4 - 导入时的 EF4 Strip 表前缀

c# - Linq to Entities 中的动态 where 子句 (OR)

c# - 选择多维数组中的所有相邻值

c# - C#中的串口通信参数不正确

entity-framework - E2L : How do you handle Foreign Keys that participate in multiple relationships?

.net - Entity Framework 中的动态 LINQ 比较日期