想要将SQL查询转换为E.F中的LINQ查询

时间:2013-07-08 10:36:17

标签: c# asp.net-mvc linq sql-to-linq-conversion

我正在使用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))

enter image description here

3 个答案:

答案 0 :(得分:2)

假设: -

  1. 您的上下文设置正确,您拥有所有导航 物业到位
  2. 您的查询是"获取所有purcahse订单 由与员工#17"
  3. 共享角色的任何员工创建

    您可以使用: -

    context.Employees.Where(x => x.Id == 17)
                     .SelectMany(x => x.Roles)
                     .SelectMany(x => x.Employees)
                     .Distinct()
                     .SelectMany(x => x.PurchaseOrders);
    

答案 1 :(得分:0)

假设您的上述查询有点奇怪而您实际上打算这样做:

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;

但要注意上述内容只有在有这样的员工的情况下才有效

答案 2 :(得分:0)

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();