带有双子查询的Linq查询
本文关键字:查询 Linq 双子 | 更新日期: 2023-09-27 18:03:14
我正在努力将以下SQL查询转换为Linq。我想我的方向是对的,但我一定是漏掉了什么。
我现在得到的错误是:
来。IQueryable不包含。contains
的定义
这让我很困惑,因为它应该是对的?
select Users.*
from Users
where UserID in (select distinct(UserID)
from UserPermission
where SupplierID in (select SupplierID
from UserPermission
where UserID = 6))
LINQ
var Users = (from u in _db.Users
where (from up in _db.UserPermissions select up.UserID)
.Distinct()
.Contains((from up2 in _db.UserPermissions
where up2.UserID == 6
select up2.SupplierID))
select u);
EDIT:我最终回到SqlCommand对象,因为这是我今天必须完成的事情,不能浪费太多时间试图弄清楚如何用Linq和EF正确地做到这一点。我讨厌代码攻击:(
我认为这里没有必要做distinct
(也许我错了)。但这里有一个更简单的版本(假设您已经正确定义了所有导航属性)
var lstUsers = DBContext.Users.Where(
x => x.UserPermissions.Any(
y => y.Suppliers.Any(z => z.UserID == 6)
)
).ToList();
如果你在Supplier
实体中有UserID
字段,如果它不是,你可以再次使用导航属性,
var lstUsers = DBContext.Users.Where(
x => x.UserPermissions.Any(
y => y.Suppliers.Any(z => z.User.UserID == 6)
)
).ToList();
Contains()
只需要一个元素,所以它不能像您编写的那样工作。试试下面的选项:
var Users = _db.Users
.Where(u => _db.UserPermissions
.Select(x => UserID)
.Distinct()
.Where(x => _db.UserPermissions
.Where(y => y.UserID == 6)
.Select(y => y.SupplierID)
.Contains(x))
);
我没有在我这边尝试,但是你可以尝试使用let关键字:
var Users = (from u in _db.Users
let distinctUsers = (from up in _db.UserPermissions select up).Distinct()
let subQuery = (from up2 in _db.UserPermissions
where up2.UserID == 6
select up2)
where
distinctUsers.SupplierID== subQuery.SupplierID &&
u.UserID==distinctUsers.UserID
select u);