核心EF外部加入,计数和分组

时间:2019-05-23 21:04:42

标签: entity-framework count core outer-join

我正在尝试将此SQL查询转换为Core 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),但这会引发错误。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

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没有运输单的集合,但是您的运输单引用了可选的运输单。

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();

希望可以使您朝正确的方向前进。如果不是,请扩展您的问题,以包括您所看到的内容,您希望看到的内容以及适用实体的定义的详细信息。