EF ICollection Vs List Vs IEnumerable Vs IQueryable [英] EF ICollection Vs List Vs IEnumerable Vs IQueryable
问题描述
示例: p>
public class Task
{
public int Id {get;组; }
public string描述{get;组; }
public virtual ICollection< SubTask> {get;组;
}
我读过某个地方,我应该使用IEnumerable来防止延期执行,那是正确?这意味着如果我的DAL方法返回IEnumerable,仍然是IQueryable,则SQL将在该时刻执行,而不是在网页中调用.TOList的时候。
那么,最好的做法是什么?我该怎么办? IEnumerable,List?,IList,ICollection?
thx
- 查询不执行,直到你真的迭代项目,也许通过做一个
.ToList( )
或foreach
。这意味着你仍然可以添加过滤器,例如Where()
。 - 扩展IEnumerable
- 只有前进的项目列表。您不能得到项目4而不通过项目0-3。
- 只读列表,您不能添加到它或从中删除。
- 仍然可能使用延期执行(IQueryable仍然是一个IEnumerable)。
- 随机访问完整列表
- 可能完全在内存(没有延迟执行,但谁知道确切的类实现这一点?)
- 支持添加和删除
- 扩展IEnumerable和ICollection
- 在IEnumerable和IList之间。
- 扩展IEnumerable
IList
:
什么是最好的取决于你的要求。通常,如果您只想显示项目,IEnumerable是够好的。至少总是使用通用变体。
so, my EF model has relationships and according to what I have seen in examples, those relationships should be done with virtual properties of ICollection.
Example:
public class Task
{
public int Id { get; set; }
public string Description { get; set; }
public virtual ICollection<SubTask> { get; set; }
}
I read somewhere that I should use IEnumerable to prevent deferred execution, is that correct? It means that if my DAL methods return IEnumerable, still of IQueryable, the SQL will be executed at that moment, and not at the moment when I call .TOList in the web page.
So, what is the best practice? What should I return? IEnumerable, List?, IList, ICollection?
thx
- Query isn't executed until you really iterate over the items, maybe by doing a
.ToList()
or aforeach
. Which means you still can add filters, like aWhere()
. - Extends IEnumerable
- Forward-only list of items. You can't get at "item 4" without passing items 0-3.
- Read-only list, you can't add to it or remove from it.
- Still might use deferred execution (IQueryable is still an IEnumerable).
- Random access to the full list
- Probably entirely in memory (no deferred execution, but who knows what the exact class does that implements this?)
- Supports adding and removing
- Extends IEnumerable and ICollection
- Is between IEnumerable and IList.
- Extends IEnumerable
What is "best" depends on your requirements. Usually though an IEnumerable is "good enough" if you only want to display items. At least always use the generic variant.
这篇关于EF ICollection Vs List Vs IEnumerable Vs IQueryable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!