我正在使用 MVC 3.5 和 EF 开发应用程序。
我已经写了SQL查询,我想在LINQ中重写,但我不知道如何使用它......
这是sql查询
select * from PurchaseOrders where CreatedById in
(select Employees_Id from EmployeeRole where Roles_Id in
(select Roles_Id from EmployeeRole where Employees_Id = 17))
我正在使用 MVC 3.5 和 EF 开发应用程序。
我已经写了SQL查询,我想在LINQ中重写,但我不知道如何使用它......
这是sql查询
select * from PurchaseOrders where CreatedById in
(select Employees_Id from EmployeeRole where Roles_Id in
(select Roles_Id from EmployeeRole where Employees_Id = 17))
假设:-
您可以使用:-
context.Employees.Where(x => x.Id == 17)
.SelectMany(x => x.Roles)
.SelectMany(x => x.Employees)
.Distinct()
.SelectMany(x => x.PurchaseOrders);
假设您的上述查询有点奇怪,并且您实际上打算这样做:
SELECT * FROM PurchaseOrders WHERE CreatedById = 17;
您的 LINQ 查询将是:
PurchaseOrders.Where(Order => Order.CreatedById = 17);
或者
var Orders = from Order in PurchaseOrders
where Order.CreatedById = 17
select Order;
看到您的更新,我想您实际上最好选择您的员工,然后选择所有采购订单,即
var Orders = Employees.Single(x => x.Id == 17).PurchaseOrders;
但请注意,仅当有这样的员工时,上述内容才会起作用
var s= (from po in _db.PurchaseOrders
join er in _db.EmployeeRoles on po.CreatedById equals er.Employees_Id
let _ser in _db.EmployeeRoles.Where(c=>c.Employees_Id == 17)
where _ser.Select(c=>c.Roles_Id).contails(er.Roles_Id)
Select po).toList();