对Linq的SQL查询

时间:2009-07-20 15:25:27

标签: sql linq linq-to-sql

如何将此查询从SQL转换为Linq:

SELECT status As 'Status',
       count(status) As 'Count'
FROM tbl_repair_order 
WHERE contract = 'con' and 
      (status = 'Parts Arr' or 
       status = 'NA' or 
       status = 'New Call' or 
       status = 'Parts Ord' or 
       status = 'Parts Req' or 
       status = 'F Work')
GROUP BY status

更新

谢谢大家,这是我用过的代码。测试并返回与上面相同的内容:

        List<string> statuses = new List<string> { "Parts Arr", "NA", "New Call", "Parts Ord", "Parts Req", "F Work"}; 

        var result = (from x in db.tbl_repair_orders
                     where x.CONTRACT == strContract
                        && statuses.Contains(x.STATUS)
                     group x.STATUS by x.STATUS into grouping
                     select new { Status = grouping.Key, Count = grouping.Count() });

        return result;

3 个答案:

答案 0 :(得分:4)

    string[] statuses = new string[] { "Parts Arr", "NA", "New Call", "Parts Ord", "Parts Req", "F Work" };
    var x = (from ro in db.tbl_repair_order
             where ro.contract == "con"
                && statuses.Contains(ro.status)
             group 0 by ro.status into grouping
             select new { Status = grouping.Key, Count = grouping.Count() });

我不知道语法是否正确(尤其是最后两行)但它应该非常接近。

我在小组之间添加了0,并根据Eamon Nerbonne在评论中的更正。另外,感谢Ryan Versaw提供了解释List和用于生成IN子句的数组的链接。

答案 1 :(得分:2)

假设您正确地连接了表格,例如

var statusCounts =
    from row in youDbNameHere.tbl_repair_order
    where row.contract == "con"
        && (row.status == "Parts Arr"
        || row.status == "NA"
        || row.status == "New Call"
        || row.status == "Parts Ord"
        || row.status == "Parts Req"
        || row.status == "F Work")
    group 0 by row.status into g
    select new { Status = g.Key, StatusCount = g.Count() };

......我看到安迪打败了我; - )

注意:

  • 你需要在“group”和“by”之间加入一个表达式,这个表达式将被评估以形成在组密钥下可访问的值集合(在你的情况下它是无关紧要的,所以零就可以了)。 / LI>
  • 如果您希望使用Linq-to-Sql或Linq-to-Entities(或其他一些IQueryable实现),请注意您的代码不会直接在C#中执行,而是被翻译(应该如此)到sql - 所以避免使用无法转换的.NET特定调用,因为这些通常会导致运行时异常或(很少)导致生成的查询在客户端被部分评估(可能会产生很大的性能成本)。 / LI>

答案 2 :(得分:-1)

至于将SQL语句转换为等效的Linq to SQL语句,您应该查看Linqer工具。我认为这个应用程序不适合用于重写整个应用程序,但它通常是学习Linq to SQL的非常有用的工具。