将我的SQL转换为LINQ

时间:2018-07-27 01:44:54

标签: c# sql linq

我正在尝试将我的SQL代码转换为C#代码linq代码。这只是我的代码的一部分,因为实际代码太长。

My SQL 
    Declare @ReportDate DateTime = NULL
    SELECT DISTINCT LotId, PenId, SUM(Head) AS TotalHead
            INTO #LotPenAlloctionListTempTable
                FROM (
                        SELECT  lp.LotId, lp.PenId, lp.HeadCountInPen  AS Head
                            FROM scoFeedlot.LotPen AS lp    

                        UNION
                        SELECT LotHistory.LotId, LotHistory.PenId, IIF(LotHistory.Direction = 1, LotHistory.Head * -1, LotHistory.Head) AS Head
                            FROM scoFeedlot.LotHistory                      
                            WHERE CAST(LotHistory.MovementDate AS DATE) > '2017-7-27' AND LotHistory.IsPending = 0 AND LotHistory.IsCancelled = 0
                    ) A GROUP BY Lotid, PenId

    Select Distinct [scoFeedlot].[Pen].PenName,[scoFeedlot].LotMaster.Lotnumber,[scoFeedlot].LotPen.HeadCountInPen
    from 
    #LotPenAlloctionListTempTable

我的C#代码

public async Task<int> GetHeadCountInPenLotPens(DateTimeOffset date)
{
    var lotPens = await _context.LotPens.ToListAsync();
    var lotHistory = await _context.LotHistories.ToListAsync();
}

1 个答案:

答案 0 :(得分:0)

在没有桌子的情况下很难说,但这应该可行:

var a = (_context.LotPen.Select(lp=> new LotPenHead 
                    { 
                       LotId= lp.LotId, 
                       PenId = lp.PenId, 
                       Head = lp.HeadCountInPen
                    })
          .Concat(_context.LotHistory
                       .Where(lh=>lh.MovementDate > new DateTime(2017,7,27) 
                               && !lh.IsPending && !lh.IsCancelled)
                       .Select(lh=>new LotPenHead 
                          { 
                               LotId= lh.LotId, 
                               PenId = lh.PenId, 
                               Head = lh.Direction == 1 ? -lh.Head : lh.Head
                          }));

var results = a.GroupBy(aa=>new {aa.LotId, aa.PenId}, aa=>aa.Head)
               .Select(aa=>new LotPenHead
                           {
                              LotId = aa.Key.LotId, 
                              PenId = aa.Key.PenId, 
                              Head=aa.Sum()
                           }).ToList();