Sql 服务器 sum(Case) 转换为 linq

Sql server sum(Case) convert to linq

我想对一段时间内在两个位置使用了多少项目求和,但我被困在控制器上

SQL查询:

select ITEMID,
       ITEM_NAME,
       ITEM_TYPE,
       sum(case when PROVIDERID = 'PR000118' then QUANTITY else 0 end) as EAST,
       sum(case when PROVIDERID = 'PR000124' then QUANTITY else 0 end) as WEST,
       sum(QUANTITY) as TOTAL
from V_ITEMUSAGE 
where DATETIME >= '2021-03-01' and DATETIME <= '2021-03-31' and ITEM_TYPE like '%%'
group by ITEMID, ITEM_NAME, ITEM_TYPE
order by TOTAL desc

视图模型:

namespace HMO.viewmodel
{
    public class Itemusageviewmodel
    {
        public IEnumerable<ITEMTYPE> ITEMTYPEs{ get; set; }
        public IEnumerable<V_ITEMUSAGE> V_ITEMUSAGEs{ get; set; }
    }
}

控制器:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Itemusage (DateTime STARTDATE, DateTime ENDDATE, String TYPE)
{
    var table = new Itemusageviewmodel
    {
        ITEMTYPEs = db.ITEMTYPE.tolist(),
        V_ITEMUSAGEs = db.V_ITEMUSAGE
                       .Where(x => m.DATETIME >= STARTDATE && x.DATETIME <= ENDDATE  && x.ITEM_TYPE.Contains(TYPE))
                       //(I don't know what code I should use here)//
    };
    return View(table);
}

我希望 Controller 的结果 V_ITEMUSAGEs 与 SQL 查询的结果相同,我如何编写 V_ITEMUSAGEs 的代码?

谢谢

你可以试试这样的

b.V_ITEMUSAGE
 .Where(x => m.DATETIME >= STARTDATE && x.DATETIME <= ENDDATE  && x.ITEM_TYPE.Contains(TYPE))
 .GroupBy(x => new { x.ITEMID, x.ITEM_NAME, x.ITEM_TYPE })
 .Select(x => new ItemUsageViewModel {
       ItemId = x.Key.ITEMID,
       ItemName = x.Key.ITEM_Name,
       ItemType = x.Key.ITEM_TYPE,
       East = x.Where(it => it.PROVIDERID == 'PR000118').Sum(it => it.QUANTITY),
       West = x.Where(it => it.PROVIDERID == 'PR000124').Sum(it => it.QUANTITY),
       Total = x.Sum(it => it.QUANTITY)
  })

其中 ItemUsageViewModel 是您定义的自定义 DTO 视图模型,应该类似于

public ItemUsageViewModel  
{
    public int ItemId {get; set;}
    public string ItemName {get; set;}
    public string ItemType {get; set;}
    public int East {get; set;}
    public int West {get; set;}
    public int Total {get; set;}
}