如何将以下LINQ查询更改为正常的sql查询

时间:2011-08-13 08:27:10

标签: c# asp.net linq sql-server-2008

我有一个查询我需要这个作为一个简单的SQL查询可以任何人帮助我。也有任何替代方法,在提到的代码中使用NorthWindDatacontext,我的代码如下

private void FetchData(int take, int pageSize)
{           
  using (NorthwindDataContext dc = new NorthwindDataContext())
  {
    var query = from p in dc.Customers
         .OrderBy(o => o.ContactName)
          .Take(take)
            .Skip(pageSize)
        select new
                        {
                          ID = p.CustomerID,
                            Name = p.ContactName,
                            Count = dc.Customers.Count()
                        };

            PagedDataSource page = new PagedDataSource();
            page.AllowCustomPaging = true;
            page.AllowPaging = true;
            page.DataSource = query;
            page.PageSize = 10;
            Repeater1.DataSource = page;
            Repeater1.DataBind();

            if (!IsPostBack)
            {
                RowCount = query.First().Count;
                CreatePagingControl();
            }
        }
    }

我按照Jon尝试但我无法获得所需的结果任何人都可以帮助我

(SELECT [t1].[CustomerID] AS [ID], [t1].[ContactName] AS [Name], (
    SELECT COUNT(*)
    FROM [dbo].[Customers] AS [t2]
    ) AS [Count]
FROM (
    SELECT TOP (10) [t0].[CustomerID], [t0].[ContactName]
    FROM [dbo].[Customers] AS [t0]
    ORDER BY [t0].[ContactName]
    ) AS [t1]
ORDER BY [t1].[ContactName]

2 个答案:

答案 0 :(得分:2)

在我看来,最简单的方法是查看LINQ to SQL正在做什么。

使用DataContext.Log将查询信息写入某种日志(例如,发送到StringWriter后可以打印出来的内容)。它并不总是最干净的SQL,但它是IMO的一个很好的起点。

我意识到这并没有回答你的特定查询的问题,但是它试图教你捕鱼而不是给你一条鱼,因为它是:)

编辑:在评论中使用RoccoC5建议的LINQPad是查看为LINQ查询生成的SQL的另一种好方法。

答案 1 :(得分:1)

这是LINQ查询根据LINQPad生成的SQL,其中@p0是Skip的行数:

SELECT [t3].[CustomerID] AS [ID], [t3].[ContactName] AS [Name], (
    SELECT COUNT(*)
    FROM [Customers] AS [t4]
    ) AS [Count]
FROM (
    SELECT [t2].[CustomerID], [t2].[ContactName], [t2].[ROW_NUMBER]
    FROM (
        SELECT ROW_NUMBER() OVER (ORDER BY [t1].[ContactName]) AS [ROW_NUMBER], [t1].[CustomerID], [t1].[ContactName]
        FROM (
            SELECT TOP (10) [t0].[CustomerID], [t0].[ContactName]
            FROM [Customers] AS [t0]
            ORDER BY [t0].[ContactName]
            ) AS [t1]
        ) AS [t2]
    WHERE [t2].[ROW_NUMBER] > @p0
    ) AS [t3]
ORDER BY [t3].[ROW_NUMBER]