异IEnumerable和IQueryable的作为一种对象集的

异IEnumerable和IQueryable的作为一种对象集的

本文介绍了在使用差异IEnumerable和IQueryable的作为一种对象集的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我了解,当我使用的的IQueryable LINQ扩展方法(和拉姆达EX pression语法),它是在对象集它们被翻译成LINQ到SQL查询。我的意思是,命令

As I understand it when I use LINQ extension methods (with lambda expression syntax) on IQueryable that is in the fact instance of ObjectSet they are translated into LINQ to SQL queries. What I mean is that command

IQueryable<User> users = db.UserSet;
var users32YearsOld = users.Where(user => user.Age == 32);

是完全一样

IQueryable<User> users = db.UserSet;
var users32YearsOld = from user in users where user.Age == 32 select user;

所以,非他们的命中数据库中,直到它们 users32YearsOld 是为周期或列举此类研究。 (希望我理解这个正确的)。

So non of them hits database until they users32YearsOld are enumerated in for cycle or such. (Hope I understand this correctly).

但什么事情发生,如果我不掩盖对象集的IQueryable 的IEnumerable ?所以,如果它的类型是的IEnumerable

But what is going to happen if I don't mask that ObjectSet as IQueryable but as IEnumerable ? So if the type of it is IEnumerable ?

IEnumerable<User> users = db.UserSet;
var users32YearsOld = users.Where(user => user.Age == 32);

时它会立刻访问数据库(如果是的话,什么时候?对上的第一行或第二)?抑或是要表现为previous命令是不会打数据库中,直到 users32YearsOld 枚举?会不会有什么不同,如果我用下面的呢?

Is it going to hit the database immediately (if so then when ? Right on the first line or on the second) ? Or is it going to behave as the previous command that is will not hit database until users32YearsOld is enumerated ? Will there be any difference if I use following instead ?

IEnumerable<User> users = db.UserSet;
var users32YearsOld = from user in users where user.Age == 32 select user;

感谢您

推荐答案

取消删除我的回答,因为我只是测试它和它的作品完全按照我描述的:

没有提到的查询将访问数据库,因为没有枚举。之间的差异的IQueryable 查询和的IEnumerable 查询是在的情况下,的IQueryable 的筛选将在数据库服务器上执行的,而在 IEnumerable的的情况下,所有对象将被从数据库装载到存储器和过滤将在完成.NET code(LINQ到对象)。正如你可以想像,通常是性能杀手。

None of mentioned queries will hit the database because there was no enumeration. The difference between IQueryable query and IEnumerable query is that in the case of IQueryable the filtering will be executed on the database server whereas in the case of IEnumerable all objects will be loaded from the database to a memory and the filtering will be done in .NET code (linq-to-objects). As you can imagine that is usually performance killer.

我在我的项目写了简单的测试:

I wrote simple test in my project:

[TestMethod]
public void Test()
{
    // ObjectQuery<Department> converted ot IEnumerable<Department>
    IEnumerable<Department> departmetns = CreateUnitOfWork().GetRepository<Department>().GetQuery();
    // No query execution here - Enumerable has also deffered exection
    var query = departmetns.Where(d => d.Id == 1);
    // Queries ALL DEPARTMENTS here and executes First on the retrieved result set
    var result = departmetns.First();
}

这篇关于在使用差异IEnumerable和IQueryable的作为一种对象集的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 18:11