SQL到LINQ转换器

时间:2011-11-10 02:27:34

标签: c# sql linq linq-to-entities entity-framework-4.1

我有一个SQL并且很难将其转换为LINQ。有没有其他工具可以将SQL转换为LINQ?我听说Linqer并尝试了它,但它不允许您查询多对多关系表的Junction / Join表。无论如何,这里是我需要转换为LINQ甚至lambda的SQL。

SELECT A.*
FROM
(              SELECT  TOP 10   T2.ID,
                T2.Name,                        
                SUM(T1.Column1 + T1.Column2 + T1.Column3) AS Total
FROM POS.dbo.Table1 T1
INNER JOIN POS.dbo.Table2 T2 on T2.ID = T1.ID
WHERE T2.ID IN 
(
    SELECT ID FROM POS.dbo.Table3 WHERE [Id] = 1
)
AND [Date] BETWEEN '2011-11-09 00:00:00' AND '2011-11-09 23:59:59'
GROUP BY T2.ID, T2.Name
ORDER BY Total DESC
) A
ORDER BY Name ASC

这是我的第一次尝试:

var query = db.Table1
              .Include(e => e.Table2)
              .Where(x => x.Date >= '2011-11-09 00:00:00'
                       && x.DateCreated <= '2011-11-09 23:59:59')
              .Where(y => y.Table2.Table3.Any(u => u.Id == 1))
              .Take(10);

3 个答案:

答案 0 :(得分:5)

我最喜欢Linq的一个方面是它将查询组合在一起,所以我将一个复杂的查询分解为子查询,让Linq重新组合它们。

使用这个基础,做这样的工作。

DateTime startDate = new DateTime(2011,11,9);
DateTime endDate   = new DateTime(2011,11,9,23,59,59);

var table3Ids = (from r in Pos.dbo.Table3 where id = 1 select r.id) ;

var query1  = 
(
    from t1 in Pos.dbo.Table1 
    where t1.Table2.Id == 1 && t1.Date >= startDate && t1.Date <= endDate
    where table3Ids.Contains(t1.Table2.Id)
    group t1 by new { t1.Table2.Id , t1.Table2.Name} into results

    select new 
    { 
        results.Key.Id , 
        results.Key.Name , 
        Total = results.Sum(r=> (r.Column1 + r.Column2 + r.Column3)) 
    } 
);


var query2 = (from r in query1 orderby r.Total descending select r).Take(10);
var query3 = (from r in query2 orderby r.Name select r);

var list = query3.ToList(); 

答案 1 :(得分:0)

旧帖子,但相关:SQL to LINQ Tool

我做了一些挖掘/询问了几个同事,看起来Linqer仍然是唯一可用的工具(至少是唯一一个众所周知的可以参与谈话的工具)

答案 2 :(得分:0)

这是我的镜头 - 在不知道实际数据结构或预期结果的情况下有点难:

var query = db.Table1
    .Join(db.Table2, table1 => table1.Id, table2 => table2.Id, (t1, t2) => new { 
        Id = t2.Id, 
        Name = t2.Name, 
        Total = (t1.Column1 + t1.Column2 + t1.Column3), 
        Date = t1.Date //you didn't use a table alias for this field, so I'm not sure which table it comes from
        })
    .Where(x => x.Date >= new DateTime(2011, 11, 9)
                && x.DateCreated <= new DateTime(2011, 11, 9, 23, 59, 59))
    .Join(db.Table3, x => x.Id, table3 => table3.Id, (x, t3) => new {
        Id = x.Id,
        Name = x.Name,
        x.Total
    })
    .Where(x => x.Id == 1)
    .OrderByDescending(x => x.Total)
    .ThenBy(x => x.Name)
    .Take(10)
    .ToList()

因为这可能是我写过的最疯狂的Linq声明,不要以为它会在第一时间起作用,但它至少是一个很好的起点。