使用实体框架将T-SQL转换为LINQ

本文关键字:转换 LINQ T-SQL 实体 框架 | 更新日期: 2023-09-27 18:10:04

我正在尝试将我的T-SQL转换为LINQ。这真让我头疼。谁能指出我在这里做错了什么吗?

T-SQL
select 
  h.DateStamp
, h.Machine
, h.SalesInvoice 
, h.Status
, sum(i.Quantity)                                           totalquantity
, sum(IIF(h.[Status]='SALES', i.Quantity, 0))               as SalesQty
, sum(IIF(h.[Status]='RETURNS', i.Quantity, 0))             as ReturnQty
, sum(IIF(h.[Status]='SALES',   i.Quantity*i.Soldsrp , 0))  as SalesGross
, sum(IIF(h.[Status]='RETURNS', i.Quantity*i.Soldsrp, 0))   as ReturnGross
, sum(IIF(h.[Status]='SALES',   i.DiscountAmount , 0))      as SalesDiscount
, sum(IIF(h.[Status]='RETURNS', i.DiscountAmount, 0))       as ReturnDiscount
, sum(IIF(h.[Status]='SALES',   i.TotalAmount , 0))         as SalesACD
, sum(IIF(h.[Status]='RETURNS', i.TotalAmount , 0))         as ReturnACD
from CSHR_SalesItems i
left join CSHR_SalesHeader h on h.SalesOrderNum = i.SalesOrderNum
where H.DateStamp between '2015-08-20 00:00:00.000' and '2015-08-27 23:59:00.000' 
group by h.DateStamp, h.Machine, h.SalesInvoice, h.[Status]

这是我的尝试把它变成LINQ与实体框架。GroundCommander是实体

using (var GC = new GroundCommanderEntities())
{
    foreach (var item in GC.CSHR_SalesItems)
    {
         var Summary =
             from i in GC.CSHR_SalesItems
             join h in GC.CSHR_SalesHeader on item.SalesOrderNum equals h.SalesOrderNum into IH
             from h in IH
             where (h.DateStamp >= dateTimePickerStart.Value && h.DateStamp <= dateTimePickerLast.Value)                 
             select new { 
                h.DateStamp,
                h.Machine,
                h.SalesInvoice,
                h.Status,
                i.Quantity //need to get the sum
             };
    }

使用实体框架将T-SQL转换为LINQ

我相信这就是你想要的。

var Summary =
    from i in GC.CSHR_SalesItems
    join h in GC.CSHR_SalesHeader on item.SalesOrderNum equals h.SalesOrderNum 
    where (h.DateStamp >= dateTimePickerStart.Value 
           && h.DateStamp <= dateTimePickerLast.Value)      
    group new { item = i, header = h} 
       by new {h.DateStamp, h.Machine, h.SalesInvoice, h.Status} into grp
    select new { 
        grp.Key.DateStamp,
        grp.Key.Machine,
        grp.Key.SalesInvoice,
        grp.Key.Status,
        TotalQuanity = grp.Sum(x => x.item.Quantity),
        SalesQty = grp.Where(x => x.header.Status == "SALES").Sum(x => x.item.Quantity),
        ...
    };

首先,我去掉了左连接因为任何时候,右边是null,无论如何都是假的。其次,我添加了将创建适当分组的组。然后在选择中,你可以对总数进行求和,我已经给了你一个如何根据其他总数的状态进行筛选的示例。