Linq查询加入子查询

时间:2012-12-18 01:46:37

标签: linq

我正在尝试使用LINQ to Entities查询重现SQL查询。以下SQL工作正常,我只是看不到如何在LINQ中这样做。我今天尝试了几个小时,但我只是遗漏了一些东西。

SELECT 
  h.ReqID,
  rs.RoutingSection
FROM ReqHeader h
JOIN ReqRoutings        rr ON rr.ReqRoutingID = (SELECT TOP 1   r1.ReqRoutingID  
                                                FROM ReqRoutings r1
                                                WHERE r1.ReqID = h.ReqID 
                                                ORDER BY r1.ReqRoutingID desc)
JOIN ReqRoutingSections rs ON rs.RoutingSectionID =  rr.RoutingSectionID  

编辑***

在查看其他示例(包括由Miki提供的示例)之后,我能够开始工作。以下是适用于我的代码:

首先,我创建了一个名为route的查询来保存我需要加入的顶级记录

var route = (from rr in context.ReqRoutings
                     where rr.ReqID == id
                     orderby rr.ID descending
                     select rr).Take(1);

然后我可以加入我的申请表和ReqRoutings查找表

var header = (from h in context.ReqHeaders
              join r in route on h.ID equals r.ReqID
              join rs in context.ReqRoutingSections on r.RoutingSectionID equals rs.ID
              where h.ID == id

              select {ReqID = h.ID,
                      RoutingSection = rs.RoutingSection}

1 个答案:

答案 0 :(得分:1)

我正在使用Northwnd示例数据库 客户,订单,员工表 在这里,我按客户和订单的employeeid获得最高1个订单组 如果这符合您的要求,请告诉我

var ord = from o in NDC.Orders
          orderby o.OrderID descending
          group o by o.CustomerID into g                     
          select new {CustomerID=g.Key,Order=g.OrderByDescending(s=>s.OrderID).First() };

var res1 = from o in ord
           join emp in NDC.Employees 
           on o.Order.EmployeeID equals emp.EmployeeID into oemp
           select new {Order=o.Order,employee=oemp };

Response.Write(res1.ToList().Count);
foreach (var order in res1)
{
    Response.Write(order.Order.CustomerID + "," + 
                     order.Order.OrderID + ","+ 
                     order.Order.EmployeeID+"<br/>");
}

//上面的代码正常工作。我试图将您的查询转换为linq并将您的datacontext名称替换为'NDC'

var ord = from rr in NDC.ReqRoutings
          orderby rr.ReqRoutingID descending
          group rr by rr.ReqID into g
          select new 
          { 
              ReqID = g.Key, 
              ReqRoutings = g.OrderByDescending(s => s.ReqRoutingID).First() 
          };

var res1 = from o in ord
           join emp in NDC.ReqRoutingSections on o.ReqRoutings.RoutingSectionID 
             equals emp.RoutingSectionID into oemp
           select new { ReqRoutings = o.ReqRoutings, employee = oemp };

Response.Write(res1.ToList().Count);
foreach (var order in res1)
{
    Response.Write(order.ReqRoutings.ReqID + "," + 
                    order.ReqRoutings.ReqRoutingID + "," + 
                    order.ReqRoutings.RoutingSectionID + "<br/>");
}

请告知是否对您有所帮助