EF4 - 多对多关系,使用 contains 和 List进行查询
我有一个使用 EF4 连接到 SQL Server 数据库的 asp.net C# 应用程序。
在数据库中,两个表 Officer
和 Geography
之间存在多对多关系 - 因此存在另一个名为 OfficerGeography
的表来连接这两个表。
通过使用此数据库创建 edmx 图,EF4 可以正确地看到这两个表之间的多对多关系。
问题
我有一个 geographyIds 的 List
,它对应于 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
,两个实体上都具有从一个到另一个的导航属性。
I have an asp.net C# application using EF4 to connect to a SQL Server database.
In the database I have a many to many relationship between two tables, Officer
and Geography
- so another table called OfficerGeography
exists which connects the two.
With this database used to create an edmx diagram, EF4 correctly sees the many to many relationship between these two tables.
The problem
I have an List<int>
of geographyIds, which correspond to the primary key of the Geography
table.
I wish to use this list to retrieve officers that have a geographyId that appear in this list. I thought the following LINQ would work:
var geographyIds = new List<int>() { 1, 2, 3, 4, 5 };
var officers = db.Officers.Where(o => o.Enabled == true && geographyIds.Contains(o.Geographies.GeographyId));
However this fails. In fact intellisense won't list any columns for o.Geographies
(because of the many to many relationship).
How can I retrieve a list of Officers where they have a GeographyId match?
Additional clarification
The OfficerGeography
database table does not appear as it's own entity in EF4. EF4 correctly sees only Officer
and Geography
, with a navigation property from one to the other on both entities.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
geographyIds.Contains()是以
一个 int 为参数,但每个军官可能有多个地理位置,因此使用any-方法一一检查。
How about
geographyIds.Contains() takes one int as parameter but each officer may have several geographies, therefor the any-method is used to check them one by one.
EF 是否将联接表映射为关系,还是将其包含为实体?
如果它已作为一个实体包含在内,您可能需要尝试
但这并不是完整的答案。如果
OfficerGeographies
表映射到 edmx 上的实体,那么您应该将其删除并在Officer
和Geography
之间添加关系/关联表并将该关系映射到连接表。Did EF map the join table as a relationship or is it included as an entity?
If it has been included as an entity, you may need to try
This isn't the whole answer, though. If the
OfficerGeographies
table is mapped to an entity on your edmx, then you should remove it and add a relationship / association between yourOfficer
andGeography
tables and map that relationship to the join table.