Select FROM 子查询而不从另一个上下文对象开始

Select FROM Subquery without starting with another context object

我正在尝试对我试图在 netCore 2.2 - EF Core 中复制的以下 MSSQL 查询建模:

SELECT
wonum,
MIN(requestdate)        AS startdate,
MAX(requestdate)        AS enddate,
MIN(laborcode)
FROM
    (
        SELECT
            wo.wonum,
            sw.requestdate,
            wo.wolablnk     AS 'laborcode'
        FROM
            DB1.dbo.web_users           wu  INNER JOIN
            DB2.dbo.workorder           wo on
            wu.laborcode = wo.wolablnk          INNER JOIN
            DB2.dbo.sw_specialrequest   sw  on
            wo.wonum = sw.wonum
    WHERE
            wo.status           in ('LAPPR', 'APPR', 'REC') AND
            sw.requestdate      > GETDATE()
    ) a   
GROUP BY
   wonum
ORDER by

我已经构建并运行了子查询部分,但这让我陷入了僵局:

        var workOrders = await _db1Context.Workorder
            .Where(r => r.Status == "LAPPR" || r.Status == "APPR" || r.Status == "REC")
            .ToListAsync();

        var specialRequests = await _db2Context.SwSpecialRequest
            .Where(r => r.Requestdate > DateTime.Now)
            .ToListAsync();

        var subQuery = (from webUser in webUsers
                        join workOrder in workOrders on webUser.Laborcode equals workOrder.Wolablnk
                        join specialRequest in specialRequests on workOrder.Wonum equals specialRequest.Wonum
                        orderby webUser.Laborcode, specialRequest.Requestdate, specialRequest.Wonum
                        select new { workOrder.Wonum, Laborcode = workOrder.Wolablnk, specialRequest.Requestdate, workOrder.Workorderid })
                        .ToList();

我不确定如何使用我构建的子查询启动我需要的查询,我什至不确定我是否在正确的轨道上。我查看了其他几个示例,但我不明白。

任何人都可以阐明这个主题并提供帮助吗?

谢谢!

编写与 SQL 相同的 LINQ 查询,不要与 ToListAsync() 混合使用。 ToListAsync() 查询发送到服务器后。此外,对于此类查询,您应该只使用一个 DbContext

var webUsers = _db1Context.Webuser;

var workOrders = _db1Context.Workorder
   .Where(r => r.Status == "LAPPR" || r.Status == "APPR" || r.Status == "REC");

var specialRequests = _db1Context.SwSpecialRequest
   .Where(r => r.Requestdate > DateTime.Now);

var subQuery = 
   from webUser in webUsers
   join workOrder in workOrders on webUser.Laborcode equals workOrder.Wolablnk
   join specialRequest in specialRequests on workOrder.Wonum equals specialRequest.Wonum
   select new 
   { 
       workOrder.Wonum, 
       Laborcode = workOrder.Wolablnk, 
       specialRequest.Requestdate
   };

var resultQuery = 
   from a in subQuery
   group a by a.Wonum into g
   select new 
   {
       Wonum = g.Key,
       StartDate = g.Min(x => x.Requestdate),
       EndDate = g.Max(x => x.Requestdate),
       Laborcode = g.Min(x => x. Laborcode)
   };

// final materialization
var result = await resultQuery.ToListAsync();