我有一個名爲Outweigh的表,它有大約50個字段。我需要創建一個類似於這個SQL查詢的Linq查詢。將SQL語句轉換爲Linq?
SELECT DISTINCT Product,
Medication,
SUM(NettWeight) as NettWt,
COUNT(DISTINCT CustCode) as Customer,
COUNT(DISTINCT DktNo)as DktNo
FROM outweigh
GROUP BY Product, Medication
ORDER BY Product, Medication
結果如下:
我已經寫了一些代碼,如下這是不是很有效。
lstOutWeigh = dbContext.Outweighs
.Where(o => o.DateOut >= StartDate && o.DateOut <= EndDate)
.ToList();
var k = from t in lstOutWeigh select new {t.Product,t.Medication,t.NettWeight};
var l = from t in k
group t by new { t.Product, t.Medication } into g
select new someclass
{
prod =g.Key.Product,
med = g.Key.Medication,
tonnes = (double) g.Sum(x => x.NettWeight),
count = g.Count()
};
有什麼建議嗎?
http://sqltolinq.com/ – SQLMason
什麼是lstOutWeigh?它是如何填充的?您可能會無意中將數據庫中的所有記錄撤回,並將linq轉換爲對象,而不是將linq轉換爲實體。 – gareththegeek
「效率不高」似乎是你問題的關鍵部分,但是這並不能提供足夠的細節讓我們真正去幫助。如果您的Linq聲明有效,但您要求提供性能幫助,請更清楚。 –