将 SQL Server 查询转换为 Linq 查询

Posted

技术标签:

【中文标题】将 SQL Server 查询转换为 Linq 查询【英文标题】:Convert SQL Server query to Linq query 【发布时间】:2015-11-29 02:01:00 【问题描述】:
select c.Name, d.First_Name, COUNT(c.Name) as qty 
from order_product_s a 
    inner join Order_s b on a.Order_Id = b.Id
    inner join Product_s c on a.Product_Id = c.Id 
    inner join Customer_s d on b.Customer_Id = d.Id 
where b.Customer_Id = 4869 
group by c.Name, d.First_Name

【问题讨论】:

抱歉,SE 不是代码编写服务。 (我们在这里帮助您编写代码,而不是为您编写代码。) 欢迎来到 Stack Overflow!请永远不要只是转储 SQL 并要求转换。至少显示一个类模型,以便导航属性和关联的多样性是可见的。此外,请说明您的目标是什么类型的 LINQ(针对实体?),展示您自己的初步努力。他们向我们解释的内容比您想象的要多。 【参考方案1】:

类似这样的:

int __UserId = 4869;

var results = 
( 
    from t in 
    (
        from a in Repo.order_product_s 
        from b in Repo.Order_s 
             .Where(bb=> bb.id == a.Order_Id)
        from c in Repo.Product_s 
             .Where(cc => cc.Id == a.Product_Id)
        from d in Repo.Customer_s  
             .Where(dd => dd.Id == b.Customer_Id)

        where b.Customer_Id == __UserId 

        select new
        
             Name = c.Name
            ,First_Name = d.First_Name
        

    )
    group t by new  t.Name , t.First_Name  into g
    select new 
     
         Name  = g.Key.Name 
        ,First_Name=g.Key.First_Name
        ,qty = g.Count( x => x.Name != null)
    

).ToList();

或更紧凑:

var results = 
( 
    from a in Repo.order_product_s 
    from b in Repo.Order_s 
         .Where(bb=> bb.id == a.Order_Id)
         // .DefaultIfEmpty() // <== makes join left join         
    from c in Repo.Product_s 
         .Where(cc => cc.Id == a.Product_Id)
         // .DefaultIfEmpty() // <== makes join left join         
    from d in Repo.Customer_s  
         .Where(dd => dd.Id == b.Customer_Id)
         // .DefaultIfEmpty() // <== makes join left join         

    where b.Customer_Id == __UserId 

    select new
    
         Name = c.Name
        ,First_Name = d.First_Name
    
    into t group t by new  t.Name , t.First_Name  into g
    select new 
     
         Name  = g.Key.Name 
        ,First_Name=g.Key.First_Name
        ,qty = g.Count( x => x.Name != null)
         // Or like this
        // ,qty = g.Select(x => x.Name).Where(x => x != null).Count()
        // and if you ever need count(distinct fieldname)
        //,qty = g.Select(x => x.GroupName).Where(x => x != null).Distinct().Count()
    

)
// .OrderBy(t => t.Name).ThenBy(t => t.First_Name).ThenBy(t => t.qty) // Order in SQL 
.ToList()
// .OrderBy(t => t.Name).ThenBy(t => t.First_Name).ThenBy(t => t.qty) // Order in .NET
;

【讨论】:

以上是关于将 SQL Server 查询转换为 Linq 查询的主要内容,如果未能解决你的问题,请参考以下文章

将 sql 查询转换为 linq 查询

将 SQL 转换为 Linq 查询

如何将 linq 查询转换为 SQL 查询?

将 SQL 子查询转换为 Linq 查询

协助将 SQL 查询转换为 LINQ 查询

将 SQL 转换为 LINQ 查询