簡體   English   中英

將SQL語句轉換為Linq?

[英]Convert SQL statement to Linq?

我有一個名為Outweigh的表,它有大約50個字段。 我需要創建一個Linq查詢,就像這個SQL查詢一樣。

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/效果很好。

http://www.linqpad.net/也是另一個很棒的工具(我/我個人在工作的地方使用)可以幫助你在這些類型的語句之間進行轉換 - 即使你喜歡使用Lambda表達式 - 在我的意見是使用LINQ查詢的最簡單方法之一。

就像是,

db.Outweighs.GroupBy(ow => new { ow.Product, ow.Medication })
    .OrderBy(g => g.Key)
    .Select(g => new
        {
            g.Key.Product,
            g.Key.Medication,
            NettWt = g.Sum(ow => ow.NettWeight),
            Customer = g.Select(ow => ow.CustCode).Distinct().Count(),
            DktNo = g.Select(ow => ow.DktNo).Distinct().Count()
        })

等同於您在問題中提供的SQL。 但是,你提出的Linq-To-Sql並不匹配。

     var t = (from  p in Context.outweigh
              group p by new {p.Product,p.Medication}  into g
              select new {Product= t.Product,Medication=t.Medication, NettWt = g.Sum(x => x.NettWeight),Customer=g.Count())
             .Distinct().orderby(new {p.Product, p.Medication});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM