gpt4 book ai didi

.net - Entity Framework 和多对多查询无法使用?

转载 作者:行者123 更新时间:2023-12-03 14:34:12 26 4
gpt4 key购买 nike

我正在尝试 EF,并且根据多对多关系进行了大量过滤。例如,我有人员、位置和人员位置表来链接两者。我还有一个角色和个人角色表。

EDIT: Tables:

Person (personid, name)

Personlocation (personid, locationid)

Location (locationid, description)

Personrole (personid, roleid)

Role (roleid, description)

EF 将为我提供人员、角色和位置实体。编辑:由于 EF 将 不是 生成 personlocation 和 personrole 实体类型,它们不能在查询中使用。

如何创建查询以提供给定位置的所有具有给定角色的人员?

在 SQL 中,查询将是
select p.*
from persons as p
join personlocations as pl on p.personid=pl.personid
join locations as l on pl.locationid=l.locationid
join personroles as pr on p.personid=pr.personid
join roles as r on pr.roleid=r.roleid
where r.description='Student' and l.description='Amsterdam'

我看过了,但似乎找不到简单的解决方案。

最佳答案

注:

由于它在 EF v1 中,我们将 不是 人员位置 人员角色生成为实体,就像 LINQ2SQL 所做的那样(上面的答案说明了 LINQ2SQL 场景,不适用于该问题。)

解决方案1:

Persons.Include("Role").Include("Location") // Include to load Role and Location
.Where(p => p.Role.Any(r => r.description == "Student")
&& p.Location.Any(l => l.description == "Amsterdam")).ToList();

这看起来很好很简单,但这会生成丑陋的 SQL 脚本
它的性能还可以。

解决方案2:

这里是分割。
   // Find out all persons in the role
// Return IQuerable<Person>
var students = Roles.Where(r => r.description == "Student")
.SelectMany(r => r.Person);

// Find out all persons in the location
// Return IQuerable<Person>
var personsInAmsterdam = Locations.Where(l=> l.description == "Amsterdam")
.SelectMany(l=>l.Person);

// Find out the intersection that gives us students in Admsterdam.
// Return List<Person>
var AdmsterdamStudents = students.Intersect(personsInAmsterdam).ToList();

将以上三步合二为一:
 //Return List<Person>
var AdmsterdamStudents = Roles.Where(r => r.description == "Student")
.SelectMany(r => r.Person)
.Intersect
(
Locations
.Where(l=> l.description == "Amsterdam")
.SelectMany(l=>l.Person)
).ToList();

它有点冗长。但这会生成干净的 SQL 查询并且性能良好。

关于.net - Entity Framework 和多对多查询无法使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/553918/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com