核心 EF 外部连接、计数和组

Core EF Outer Join,Count & Group

我正在尝试将此 SQL 查询转换为核心 EF:

SELECT w.IdShippingBatch, w.BookingNumber, COUNT(c.IdShippingOrder) AS ShippingOrders, w.CreatedOn, w.ModifiedOn
    FROM dbo.Shipping`enter code here`Batch AS w LEFT OUTER JOIN
            dbo.ShippingOrders AS c ON w.IdShippingBatch = c.IdShippingBatch
    WHERE (w.IdCompany = 2) AND (w.IdDealer = 1)
    GROUP BY w.IdShippingBatch, w.BookingNumber, w.CreatedOn, w.ModifiedOn

我尝试了多种解决方案,包括这里的几种。我最近的尝试看起来像:

var data = (from w in _context.ShippingBatch
    join c in _context.ShippingOrders on w.IdShippingBatch equals c.IdShippingBatch into t1
    where w.IdCompany == idCompany && w.IdDealer == idDealer
    from t2 in t1.DefaultIfEmpty()
    group t2 by new { w.IdShippingBatch, w.BookingNumber, w.CreatedOn, w.ModifiedOn } into t3
    select new ShippingBatchDTO
    {
        IdShippingBatch = t3.Key.IdShippingBatch,
        BookingNumber = t3.Key.BookingNumber,
        ShippingOrders = t3.Count(),
        CreatedOn = t3.Key.CreatedOn,
        ModifiedOn = t3.Key.ModifiedOn
    });

我也试过添加 t3.count(m => m.something != null),但会引发错误。

EF 的一个要点是映射实体之间的关系,这样您就可以利用 LINQ 并让 EF 组成一个 SQL 查询,而不是试图用 LINQ-QL 替换 SQL .

如果您的 ShippingBatch 映射到 ShippingOrders 集合...

var batches = _context.ShippingBatch
  .Where(x => x.IdCompany == idCompany && x.IdDealer == idDealer)
  .Select(x => new ShippingBatchDTO
  {
        IdShippingBatch = x.IdShippingBatch,
        BookingNumber = x.BookingNumber,
        ShippingOrders = x.ShippingOrders.Count(),
        CreatedOn = x.CreatedOn,
        ModifiedOn = x.ModifiedOn    
  }).ToList();

如果您的 ShippingBatch 没有 ShippingOrders 集合,但您的 ShippingOrder 引用了一个可选的 ShippingBatch。

var batches = _context.ShippingOrder
  .Where(x => x.ShippingBatch != null 
    && x.ShippingBatch.IdCompany == idCompany 
    && x.ShippingBatch.IdDealer == idDealer)
  .GroupBy(x => x.ShippingBatch)
  .Select(x => new ShippingBatchDTO
  {
        IdShippingBatch = x.Key.IdShippingBatch,
        BookingNumber = x.Key.BookingNumber,
        ShippingOrders = x.Count(),
        CreatedOn = x.Key.CreatedOn,
        ModifiedOn = x.Key.ModifiedOn    
  }).ToList();

这应该能让您朝着正确的方向前进。如果没有,请扩展您的问题以包括您所看到的内容的详细信息,以及您希望看到的内容以及适用实体的定义。