问题描述
所以我被告知几次使用以上框架应用程序时禁用延迟加载,并且了ToList()将迫使查询在我的仓库来执行。有人告诉我,我会避免一定的陷阱我可能会遇到,如果我使用AsEnumerable()。
So I've been advised a few times to disable lazy loading when building an application with the above frameworks, and that ToList() will force the queries in my repository to execute. I was told that I would avoid certain "traps" I might run into if I used AsEnumerable().
在最近的问题,但是,我在code例子包括一堆了ToList()秒,并怔了一定数量的放心我的人IEnumerable的要好得多返回。
On a recent question, however, I included a bunch of ToList()s in my code examples, and startled a number of people that assured me IEnumerable is much better to return.
我现在是彻底糊涂了,至少可以这样说。
I'm thoroughly confused now, to say the least.
我应该回来了IEnumerable在我的资料库,然后将它们转换在我看来机型列表?我应该使用了ToList()在直道我的仓库就像我从前?当时我想留在第一时间启动延迟执行?
Should I be returning IEnumerable in my repository, then converting them to List in my view models? Should I use ToList() straightaway in my repository like I was before? Was I suppose to leave deferred execution enabled in the first place?
吉米尼圣诞节...
编辑:
所以,是,我禁用延迟加载,根据前面的建议,我应该再重新启用它,从我的仓库返回的IEnumerable / IQueryable的,以及收集转换成一个列表,我的视图模型,如果需要的话?
So, being that I disabled lazy loading, based on earlier advice, should I then re-enable it, return IEnumerable / IQueryable from my repository, and convert the collection to a List in my view models, if needed?
下面的一个同伙IEnumerable的渴望与执行问题的答案,而我是在IM pression只有了ToList()将迫使查询立即执行下。
One of the answers below associates IEnumerable with eager execution, while I was under the impression that only ToList() would force immediate execution of the query.
我碰到这,this,和this所有包含有关这一问题的一些有趣的讨论。
I stumbled across this, this, and this that all contain some interesting discussion related to this question.
推荐答案
呼叫了ToList()
,返回一个的IEnumerable
在你的仓库,如果:
Call ToList()
, returning an IEnumerable
in your repository, if:
- 您要控制提供给消费者(即你不希望它们运行查询就可以了)的输出设定和
- 您不介意急于执行。
返回的IQueryable
或的IEnumerable
通过 AsEnumerable()
,在你的仓库,如果:
Return IQueryable
, or IEnumerable
via AsEnumerable()
, in your repository if:
- 您不介意你的客户运行查询的输出设定和
- 您要延迟执行。
另请参见结果
http://thinkbeforecoding.com/post/2009/01/19/Repositories-and-IQueryable-the-paging-case
这篇关于ASP.NET MVC2与实体框架4 - AsEnumerable()或了ToList()的资料库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!