0

我正在尝试使用 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}
4

1 回答 1

1

我正在使用 Northwnd 示例数据库 Customers,Orders,Employees 表在这里我按客户和订单的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 并将您的数据上下文名称替换为“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/>");
}

请告诉它是否对您有帮助

于 2012-12-18T10:52:35.883 回答