在EF Core 6中,如何将SQL查询转换为Linq表达式,以便在各种条件下进行Join?

g9icjywg  于 2022-12-20  发布在  其他
关注(0)|答案(2)|浏览(141)

这是我的SQL查询,我试图转换:

SELECT TOP (10) 
    t1.ProductName, t2.ProductName, 
    COUNT(DISTINCT t1.OrderId) AS num_orders
FROM 
    Reports t1 
JOIN
    Reports t2 ON t1.OrderId = t2.OrderId
               AND t1.ProductId < t2.ProductId
GROUP BY
    t1.ProductName, t2.ProductName
ORDER BY 
    num_orders DESC

如您所见,在“on”中,orderId必须相同,并且其中一个的productId必须小于另一个。
这是我迄今为止所取得的成就(非常不完整):

var reportData = await (from t1 in this.Context.Reports 
                        join t2 in this.Context.Reports 
                             on t1.OrderIdequals t2.OrderId
                        where t1.ProductId < t2.ProductId
                        into GroupedData
                        orderby GroupedData.Key
                        select new 
                        {
                           GroupedData
                        }).ToListAsync();

如果我把一个表达式的“and”放在“on”中,我会得到一个错误,我已经尝试在一个单独的“where”中这样做,但它仍然不起作用。
此外,选择是不完整的,因为我还没有设法让所有上述代码的工作,所以不要给予它任何重要性。
我最接近让它为我工作的时候,我得到了这个人得到的同样的错误:How can I use Linq expression for Join with GroupBy in EF Core 3.1
这是我用来搜索信息的页面,但它没有显示我要查找的内容:https://learn.microsoft.com/en-us/ef/core/querying/complex-query-operators
我也用过Linqerthis repository of SQL to Linq,但是我用不了,我是大三学生:(
有人能帮助我或推荐我在哪里查找信息吗?

rt4zxlrg

rt4zxlrg1#

试试这个

var reportData = (from t1 in Context.Reports
                             join t2 in Context.Reports on t1.OrderId equals t2.OrderId
                             select new { t1 = t1, t2 = t2 }
                 ).Where(x => x.t1.ProductId < x.t2.ProductId)
                  .GroupBy(x => new { t1Id = x.t1.ProductId, t2Id = x.t2.ProductId })
                  .Select(x => new { t1ProductName = x.First().t1.ProductName, x.First().t2.ProductName, num_Orders = x.Select(y => y.t1.OrderId).Distinct().Count()})
                  .OrderByDescending(x => x.num_Orders);
sg3maiej

sg3maiej2#

试试这个,

var result = (from t1 in Reports
             join t2 in Reports on t1.OrderId equals t2.OrderId
             where t1.ProductId < t2.ProductId
             group new { t1, t2 } by new { t1.ProductName, t2.ProductName } into g
             let numOrders = g.Select(x => x.t1.OrderId).Distinct().Count()
             orderby numOrders descending
             select new
             {
                 ProductName1 = g.Key.ProductName,
                 ProductName2 = g.Key.ProductName2,
                 NumOrders = numOrders
             }).Take(10);

相关问题