【问题标题】:EF4 - Many to many relationship, querying with contains and List<int>EF4 - 多对多关系,使用 contains 和 List<int> 进行查询
【发布时间】:2011-02-21 12:50:43
【问题描述】:

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

在数据库中,OfficerGeography 这两个表之间存在多对多关系,因此存在另一个名为 OfficerGeography 的表将两者连接起来。

使用这个用于创建 edmx 图的数据库,EF4 可以正确地看到这两个表之间的多对多关系。

问题
我有一个 List&lt;int&gt; 的 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));

但是这失败了。事实上,intellisense 不会列出 o.Geographies 的任何列(因为多对多关系)。

如何检索与 GeographyId 匹配的军官列表?

补充说明
OfficerGeography 数据库表在 EF4 中不会作为它自己的实体出现。 EF4 正确地只看到 OfficerGeography,在两个实体上都具有从一个到另一个的导航属性。

【问题讨论】:

  • 您在 edmx 上有 OfficerGeography 实体吗?

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


【解决方案1】:

怎么样

var officers = db.Officers
    .Where(o => o.Enabled == true 
        && o.Geographies.Any(g => geographyIds.Contains(g.Id)));

geographyIds.Contains() 以一个int作为参数,但每个官员可能有多个地理位置,因此使用any-方法一一检查。

【讨论】:

    【解决方案2】:

    EF 是将连接表映射为关系还是作为实体包含在内?

    如果已作为实体收录,可能需要尝试

    o.OfficerGeographies.GeographyId
    

    不过,这还不是全部答案。如果 OfficerGeographies 表映射到 edmx 上的实体,则应将其删除并在 OfficerGeography 表之间添加关系/关联,并将该关系映射到连接表。

    【讨论】:

    • @kirk-broadhurst OfficerGeographies 表不显示为实体。 EF4 只看到OfficerGeographies 之间的多对多关系。这些实体中的每一个都有另一个作为导航属性。
    猜你喜欢
    • 1970-01-01
    • 2021-09-08
    • 1970-01-01
    • 2014-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-24
    相关资源
    最近更新 更多