【问题标题】:Convert Linq to SQL将 Linq 转换为 SQL
【发布时间】:2012-07-30 06:51:38
【问题描述】:

我在网上研究过,大多数结果都是从 sql 转换为 linq,很少有 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);
      }
    }

【问题讨论】:

  • 您可以随时使用分析器查看生成的实际查询,或插入某种形式的日志记录。
  • 您好,我在 Microsoft Visual Studio 中使用 SQL Server。
  • 为什么不试试Linqpad,它会帮助你理解事物,你也可以看到生成的sql。

标签: asp.net sql linq


【解决方案1】:

您可以尝试在LinqPad 中运行 LINQ 语句。有关如何使用 LinqPad 的示例,check the answer here

它有一个选项卡来显示生成的 SQL 语句。

【讨论】:

  • 我已经下载了LinqPad,但是如何使用呢?
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-24
    • 2012-08-20
    相关资源
    最近更新 更多