【问题标题】:Can anyone help me converting SQL to linq query. I tried but failed谁能帮我将 SQL 转换为 linq 查询。我试过但失败了
【发布时间】:2017-07-24 16:56:57
【问题描述】:

这是我的 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
    };

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

【问题讨论】:

  • 你追求的结果是什么?
  • 查看 sql 查询。我想在 LINQ 中创建精确查询
  • 我已经试过但无法下载。

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


【解决方案1】:

您以后不能在 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()
    };

【讨论】:

  • 几乎 - 只是看到在 SQL 中有 SumCount 用于字段
  • NoteCount = grp.Count(x=>x.notes!=null),无法在此处访问“笔记”
【解决方案2】:

用于将 SQL 转换为 LINQ,

  1. 将子选择翻译为单独的变量

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

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

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

  5. 使用连接变量模拟左连接,然后从连接变量执行另一个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()
          };

我在您的 SQL 中保留了 LeadID 定义,但这对我来说看起来不正确。

【讨论】:

  • 感谢您的回答,但这些行给出了错误。 LeadID = ldnoteg.ld.LeadId.Count(), NoteCount = ldnoteg.note.noteCount.Sum(), Calls = ldnoteg.ld.CallResultId.Count()
  • 抱歉,我没有正确翻译组访问 - 我已修复它。查看 LINQ 与 SQL,很明显 SQL 存在许多错误:LeadId 不应该是 countcount(ld.LeadId)count(ld.CallResultId) 没有 DISTINCT 之间没有区别。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多