我有這樣的實體:我該如何改進這個Linq查詢(一種旋轉)?
public class Delivery
{
public int Id { get; set; }
public int ProductId { get; set; }
public int CustomerId { get; set; }
public int Quantity { get; set; }
public DateTime DeliveryDate { get; set; }
public virtual Product Product { get; set; }
public virtual Customer Customer { get; set; }
}
我想顯示按周交貨,所以我寫這篇文章的查詢:
public override IEnumerable GetModelData(ApplicationDbContext context)
{
return context.Deliveries.GroupBy(x => x.Product).Select(x => new
{
Id=x.Key.Id,
Product = x.Key.Name,
Wk1 =(int?) x.Where(a => SqlFunctions.DatePart("wk", a.DeliveryDate) == 1).Sum(a => a.Quantity),
...
...
...
Wk46 = (int?)x.Where(a => SqlFunctions.DatePart("wk", a.DeliveryDate) == 46).Sum(a => a.Quantity),
Wk47 = (int?)x.Where(a => SqlFunctions.DatePart("wk", a.DeliveryDate) == 47).Sum(a => a.Quantity),
Wk48 = (int?)x.Where(a => SqlFunctions.DatePart("wk", a.DeliveryDate) == 48).Sum(a => a.Quantity),
Wk49 = (int?)x.Where(a => SqlFunctions.DatePart("wk", a.DeliveryDate) == 49).Sum(a => a.Quantity),
Wk50 = (int?)x.Where(a => SqlFunctions.DatePart("wk", a.DeliveryDate) == 50).Sum(a => a.Quantity),
Wk51 = (int?)x.Where(a => SqlFunctions.DatePart("wk", a.DeliveryDate) == 51).Sum(a => a.Quantity),
Wk52 = (int?)x.Where(a => SqlFunctions.DatePart("wk", a.DeliveryDate) == 52).Sum(a => a.Quantity),
}).ToList();
}
是否有可能得到一個更小的查詢的預期目標?
我在這一刻有大約100個樣本在交貨數據庫表中排成行,而我有這種填充方式來獲取數據並不是最好的。
該查詢正在工作,我只想知道你是否想到了寫這種查詢的更好方法。
我不明白你的邏輯或你的代碼。你說你想按周顯示交貨。你能詳細說明嗎?什麼是'Wk1,Wk2等'? –
我正在顯示一個包含53列的表格,第一列是ProductName,接下來的52列是從week1(wk1)到week52(wk52)一年中的幾周。在上面的查詢中,我刪除了一些行以顯示較小的查詢。 –
哇,你檢查了生成的SQL嗎?由於關於分組結果的52個Where語句,我期望它是一個怪物。你用什麼ORM btw? –