比较LINQ to Entities的AsQueryable和AsEnumerable方法

 
例一:

C#程序:
using (testContext context = new testContext())
{
    var query = (from item in context.Users.AsQueryable()
                    where item.id > 10
                    select item.id).ToList();
    var query2 = (from item in context.Users.AsEnumerable()
                    where item.id > 10
                    select item.id).ToList();
}

服务器端sql:

--AsQueryable
Select 
[Extent1].[id] AS [id]
FROM [dbo].[User] AS [Extent1]
Where [Extent1].[id] > 10
--AsEnumerable
Select 
[Extent1].[id] AS [id], 
[Extent1].[usn] AS [usn], 
[Extent1].[pwd] AS [pwd], 
[Extent1].[created] AS [created]
FROM [dbo].[User] AS [Extent1]

  例二:

C#程序:

using (testContext context = new testContext())
{
    var query = (from item in context.Users.AsQueryable()
                    where item.id > 10
                    orderby item.id ascending
                    select item.id).Skip(20).Take(20).ToList();
    var query2 = (from item in context.Users.AsEnumerable()
                    where item.id > 10
                    orderby item.id ascending
                    select item.id).Skip(20).Take(20).ToList();
}

  服务器端sql:

--AsQueryable
Select TOP (20) 
[Filter1].[id] AS [id]
FROM ( Select [Extent1].[id] AS [id], row_number() OVER (ORDER BY [Extent1].[id] ASC) AS [row_number]
    FROM [dbo].[User] AS [Extent1]
    Where [Extent1].[id] > 10
)  AS [Filter1]
Where [Filter1].[row_number] > 20
orDER BY [Filter1].[id] ASC
--AsEnumerable
Select 
[Extent1].[id] AS [id], 
[Extent1].[usn] AS [usn], 
[Extent1].[pwd] AS [pwd], 
[Extent1].[created] AS [created]
FROM [dbo].[User] AS [Extent1]

  小结

AsQueryable是在数据库中查询再返回数据,AsEnumerable是从数据库读取全部数据再在程序中查询,其效果和ToList相同。 

posted @ 2018-09-28 14:36  唔愛吃蘋果  阅读(383)  评论(0编辑  收藏  举报