2012-07-30 103 views
3

我在网上进行了研究,大多数结果都是从sql转换到linq,很少有linq到sql。将Linq转换为SQL

这是我要转换为SQL代码:

using (CommerceEntities db = new CommerceEntities()) 
    { 
    try 
     { 
     var query = (from ProductOrders in db.OrderDetails 
         join SelectedProducts in db.Products on ProductOrders.ProductID 
         equals SelectedProducts.ProductID 
         group ProductOrders by new 
          { 
          ProductId = SelectedProducts.ProductID, 
          ModelName = SelectedProducts.ModelName 
          } into grp 
         select new 
          { 
          ModelName = grp.Key.ModelName, 
          ProductId = grp.Key.ProductId, 
          Quantity = grp.Sum(o => o.Quantity) 
          } into orderdgrp where orderdgrp.Quantity > 0 
         orderby orderdgrp.Quantity descending select orderdgrp).Take(5); 

        RepeaterItemsList.DataSource = query; 
        RepeaterItemsList.DataBind(); 
     } 
    catch (Exception exp) 
     { 
     throw new Exception("ERROR: Unable to Load Popular Items - " + 
          exp.Message.ToString(), exp); 
     } 
    } 
+0

您可以随时使用Profiler来看看实际的查询生产,或插入某种形式的日志记录。 – 2012-07-30 06:53:43

+0

嗨,我在Microsoft Visual Studio中使用SQL Server。 – user1529419 2012-07-30 06:56:42

+1

你为什么不尝试Linqpad,它会帮助你理解事物,你也可以看到生成的SQL。 – 2012-07-30 06:58:23

回答

2

您可以尝试在LinqPad运行LINQ声明。有关如何使用LinqPad的示例,请参阅check the answer here

它有一个标签来显示生成的SQL语句。

+0

我已经下载了LinqPad,但如何使用它? – user1529419 2012-07-30 09:07:22

1

Here's an article on logging in LINQ to SQL。它允许您指定发送查询的TextWriter。

基本上,你可以写这样的事情:

db.Log = new System.IO.StreamWriter("linq-to-sql.log") { AutoFlush = true }; 

...其中db是你的数据上下文。

在SQL你会写这样的事情(虽然生成的代码看起来有很多不同的,因为它是自动生成的):

SELECT TOP 5 Products.ModelName, Products.ProductID, SUM(OrderDetails.Quantity) qty 
FROM OrderDetails 
INNER JOIN Products ON OrderDetails.ProductID = Products.ProductID 
GROUP BY Products.ProductID, Products.ModelName 
HAVING qty > 0 
ORDER BY qty DESC