SQL 涉及多个 GroupJoin 的 LINQ

SQL to LINQ Involving Multiple GroupJoin

我有一个 SQL 查询,想转换成 LINQ 方法语法 (Lambda),但似乎我被困在多组连接中,这让我很困惑。 下面是我想改成 LINQ

的 SQL
select MerchantUserId, usex.Nickname, MAX(OrderTransaction.CreatedDate) as LastOrderDate, sd.Url, st.Name as storename
from OrderTransaction
    left join UserExtend usex
    on usex.Id = OrderTransaction.MerchantUserId
    left join StoreDomain sd 
    on sd.StoreId = usex.StoreId
    left join store st
    on st.id = sd.StoreId
where OrderTransaction.Status <> 8
    and sd.IsPrimary = 1    
group by MerchantUserId,usex.Nickname,sd.Url,st.Name
order by LastOrderDate desc

下面是我尝试 link 所有三个表的查询。我 link 将 3 个表放在一起是否正确?

    var list = _ApplicationDbContext.UserExtend
.GroupJoin(_ApplicationDbContext.OrderTransaction, usex => usex.Id, ord => ord.MerchantUserId, (usex, ord) => new { usex, ord})
.GroupJoin(_ApplicationDbContext.StoreDomain, usexOrd => usexOrd.usex.StoreId, sd => sd.StoreId, (usexOrdStoreDom, sd) => new { usexOrdStoreDom , sd})
.GroupJoin(_ApplicationDbContext.Store, usexOrdStoreDom => usexOrdStoreDom.usexOrdStoreDom.usex.StoreId, st => st.Id, (usexOrdStoreDomStore , st ) => new { usexOrdStoreDomStore, st })

与您的 SQL 查询等效的是以下 link 短语。 GroupJoin 适用于需要将一个值与多个值匹配的情况。

更多信息可以参考这个link:Linq to Entities join vs groupjoin

var list = _ApplicationDbContext.UserExtend.Join(_ApplicationDbContext.OrderTransaction,
      usex => usex.Id,
      ord => ord.MerchantUserId,
      (usex, ord) => new { usex, ord })
      .Join(_ApplicationDbContext.StoreDomain,
      usexOrd => usexOrd.usex.StoreId,
      sd => sd.StoreId,
      (usexOrd, sd) => new { usexOrd, sd })
      .Join(_ApplicationDbContext.Store,
      usexOrdStoreDom => usexOrdStoreDom.sd.StoreId,
      st => st.Id,
      (usexOrdStoreDom, st) => new { usexOrdStoreDom, st })
      .GroupBy(a => new { a.usexOrdStoreDom.usexOrd.ord.MerchantUserId, a.usexOrdStoreDom.usexOrd.usex.Nickname, a.usexOrdStoreDom.sd.Url, a.st.Name, a.usexOrdStoreDom.usexOrd.ord.CreatedDate })
      .OrderBy(a => a.Key.CreatedDate)
      .Select(a => new
      {
         MerchantUserId = a.Key.MerchantUserId,
         Nickname = a.Key.Nickname,
         Url = a.Key.Url,
         storename = a.Key.Name,
         LastOrderDate = a.Max(x => x.usexOrdStoreDom.usexOrd.ord.CreatedDate)
      })
      .ToList();