2017-07-24 56 views
-4

這裏是我的SQL查詢SQL中工作正常:任何人都可以幫助我將SQL轉換爲linq查詢。我嘗試,但未能

select ld.FolderId, count(ld.LeadId) LeadID, sum(note.noteCount) NoteCount, count(ld.CallResultId) Calls 
from LeadsDetails ld 
    left join 
    (
     select lnh.LeadId, Count(lnh.NoteId) as noteCount 
     from [dbo].[LeadNoteHistory] lnh 
     group by lnh.LeadId 
    )note 
    on note.LeadId=ld.LeadId 
group by ld.FolderId 

我試過 -

var query = 
    from lead in _context.LeadsDetails 
    join note in _context.LeadNoteHistories 
    on lead.LeadId equals note.LeadId into g 
    from notes in g.DefaultIfEmpty() 
    group lead by lead.FolderId into grp 
    select new 
    { 
     FolderId = g.FolderId, 
     LeadID = g.LeadId, 
     NoteCount = notes.NoteId, 
     Call = lead.CallResultId 
    }; 

不能得到正確的結果。請告訴我做錯了什麼。

+0

你之後的結果是什麼? – SandPiper

+0

請參閱sql查詢。我想創建精確查詢LINQ – James

+0

http://www.sqltolinq.com/ –

回答

0

以後您不能在select子句中訪問變量'g'。你需要使用變量'grp'。您還需要通過修改最終組。我試着修改,看看,如果這個工程:

var query = 
    from lead in _context.LeadsDetails 
    join note in _context.LeadNoteHistories 
    on lead.LeadId equals note.LeadId into g 
    from notes in g.DefaultIfEmpty() 
    group new {lead,notes} lead by lead.FolderId into grp 
    select new 
    { 
     FolderId = grp.Key, 
     LeadID = grp.Count(), 
     NoteCount = grp.Count(x=>x.notes!=null), 
     Call = grp.Count() 
    }; 
+0

差不多 - 只是看到在SQL中有'Sum'和'Count'字段 –

+0

Thanks @GiladGreen。更新了答案 – madcap

+0

NoteCount = grp.Count(x => x.notes!= null),無法訪問此處的'筆記' – James

0

要翻譯SQL到LINQ,

  1. 翻譯子選擇作爲獨立變量

  2. 翻譯在LINQ條款順序爲每個條款,留下一元運營商(DISTINCTTOP等)作爲適用於整個LINQ查詢的函數。

  3. 使用表別名作爲範圍變量。使用列別名作爲匿名類型字段名稱。對於多列

  4. 左連接

  5. 使用匿名類型(new { })是通過使用連接變量做是另一回事from從加入變量,然後.DefaultIfEmpty()模擬。

這裏是你的SQL翻譯:

var rightside = from lnh in dbo.LeadNoteHistory 
       group lnh by lnh.LeadId into lnhg 
       select new { LeadId = lnhg.Key, noteCount = lnhg.Count() }; 

var ans = from ld in dbo.LeadsDetails 
      join note in rightside on ld.LeadId equals note.LeadId into notej 
      from note in notej.DefaultIfEmpty() 
      group new { ld, note } by ld.FolderId into ldnoteg 
      select new { 
       FolderId = ldnoteg.Key, 
       LeadID = ldnoteg.Select(lng => lng.ld.LeadId).Count(), 
       NoteCount = ldnoteg.Select(lng => lng.note.noteCount).Sum(), 
       Calls = ldnoteg.Select(lng => lng.ld.CallResultId).Count() 
      }; 

我離開LeadID定義你的SQL,但不看我的權利。

+0

感謝您的回答,但是這些行提供了錯誤。 LeadID = ldnoteg.ld.LeadId.Count(), NoteCount = ldnoteg.note.noteCount.Sum(), Calls = ldnoteg.ld.CallResultId.Count() – James

+0

對不起,我沒有正確地翻譯組訪問 - 我修好了它。看看LINQ與SQL的關係,很明顯SQL存在一些錯誤:LeadId不應該是count,'count(ld.LeadId)'和'count(ld.CallResultId)之間沒有區別'沒有'DISTINCT'。 – NetMage

相關問題