2017-07-24 23 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

相关问题