[英]EF ICollection Vs List Vs IEnumerable Vs IQueryable
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. 所以,我的EF模型有关系,根据我在例子中看到的,这些关系应该用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? 我在某处读到了我应该使用IEnumerable来防止延迟执行,这是正确的吗? 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.
这意味着如果我的DAL方法返回IEnumerable,仍然是IQueryable,那么SQL将在那一刻执行,而不是在我在网页中调用.TOList时。
So, what is the best practice? 那么,最佳做法是什么? What should I return?
我该怎么回事? IEnumerable, List?, IList, ICollection?
IEnumerable,List?,IList,ICollection?
thx 谢谢
IQueryable
: IQueryable
:
.ToList()
or a foreach
. .ToList()
或foreach
。 Which means you still can add filters, like a Where()
. Where()
。 What is "best" depends on your requirements. 什么是“最好”取决于您的要求。 Usually though an IEnumerable is "good enough" if you only want to display items.
通常,如果您只想显示项目,IEnumerable“足够好”。 At least always use the generic variant.
至少总是使用通用变体。
Another difference in case of EF is that the IEnumerable is not executing the query to the DB untill you really enumerate the list. EF的另一个区别是IEnumerable没有执行查询到DB,直到您真正枚举列表。 While the IList will execute the query and fetch the items in memory.
IList将执行查询并获取内存中的项目。 I had a strange behaviour with caching.
我有一个奇怪的缓存行为。 Chaching the IEnumarable didn't store the items but rather the unfetched enumeration, everytime i would call the cache and fetch the enumeration for some purpose, it would go to the DB and execute the query, so caching was useless.
追逐IEnumarable并没有存储项目,而是存储了未获取的枚举,每当我调用缓存并为某种目的获取枚举时,它将转到数据库并执行查询,因此缓存是无用的。 But a ToList() on the enumeration fetched the items and stored the items in the cache, so only 1 trip to the DB for this.
但是枚举上的ToList()获取了项目并将项目存储在缓存中,因此只有1次访问数据库。 Find more in this post: http://www.dailycode.info/BlogV2/post/entityframework-adding-ienumerable-to-cache
在这篇文章中找到更多: http : //www.dailycode.info/BlogV2/post/entityframework-adding-ienumerable-to-cache
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.