c# – 为什么以下linq到sql查询生成一个子查询?

前端之家收集整理的这篇文章主要介绍了c# – 为什么以下linq到sql查询生成一个子查询?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我做了以下查询
var list = from book in books
          where book.price > 50
          select book;

list = list.Take(50);

我会期望以上产生如下:

SELECT top 50 id,title,price,author
FROM Books
WHERE price > 50

但它会产生:

SELECT
[Limit1].[C1] as [C1]
[Limit1].[id] as [Id],[Limit1].[title] as [title],[Limit1].[price] as [price],[Limit1].[author]
FROM (SELECT TOP (50) 
             [Extent1].[id] as as [Id],[Extent1].[title] as [title],[Extent1].[price] as [price],[Extent1].[author] as [author]
      FROM Books as [Extent1]
      WHERE [Extent1].[price] > 50
     ) AS [Limit1]

为什么上述linq查询生成一个子查询,C1是从哪里来的?

解决方法

你仍然可以像这样清洁:
var c = (from co in db.countries
                    where co.regionID == 5
                    select co).Take(50);

这将导致:

Table(country).Where(co => (co.regionID = Convert(5))).Take(50)

相当于:

SELECT TOP (50) [t0].[countryID],[t0].[regionID],[t0].[countryName],[t0].[code]
FROM [dbo].[countries] AS [t0]
WHERE [t0].[regionID] = 5

编辑:评论,它不一定是因为单独的Take(),你仍然可以这样使用它:

var c = (from co in db.countries
                     where co.regionID == 5
                     select co);
            var l = c.Take(50).ToList();

结果与以前相同.

SELECT TOP (50) [t0].[countryID],[t0].[code]
FROM [dbo].[countries] AS [t0]
WHERE [t0].[regionID] = @p0

你写的IQueryable = IQueryable.Take(50)的事实在这里很棘手.

猜你在找的C#相关文章