任何人都可以帮助我将SQL转换为linq查询。我试过但失败了

时间:2017-07-24 16:56:57

标签: c# sql linq linq-to-sql

这是我在SQL中正常工作的SQL查询:

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
    };

无法获得正确的结果。请告诉我我做错了什么。

2 个答案:

答案 0 :(得分: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()
    };

答案 1 :(得分:0)

将SQL转换为LINQ,

  1. 将子选择转换为单独的变量

  2. 以LINQ子句顺序翻译每个子句,将monadic运算符(DISTINCTTOP等)作为应用于整个LINQ查询的函数。

  3. 使用表别名作为范围变量。使用列别名作为匿名类型字段名称。

  4. 对多列使用匿名类型(new { }

  5. 通过使用连接变量并从连接变量执行另一个from,然后.DefaultIfEmpty()来模拟左连接。

  6. 这是你的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()
              };
    

    我在SQL中保留了LeadID定义,但这对我来说并不合适。