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
IQueryable,IList,IDictionary,ICollection inherits IEnumerable Interface. All the interfaces of type collection will inherits IEnumerable Interface. Differences Between IEnumerable and IQueryable IEnumerable:-when you are running a query which returns of type IEnumerable.
IEnumerable contains only GetEnumerator() method, like read-only iterate. ICollection is one step ahead of IEnumerable. If we want some more functionality like Add or remove element, then it is better to go with ICollection because we cannot achieve that with IEnumerable. ICollection extends IEnumerable.
ICollection<T> is an interface that exposes collection semantics such as Add() , Remove() , and Count . Collection<T> is a concrete implementation of the ICollection<T> interface. IList<T> is essentially an ICollection<T> with random order-based access.
Here is a test that i have setup this evening. It was made to prove something different, but the outcome was not quite as i expected. I'm running a test with 10000 random queries on an IQueryable and while testing i found out that if i do the same on a List, my test is 20 times faster.
IQueryable
:
.ToList()
or a foreach
. Which means you still can add filters, like a Where()
.IEnumerable
:
IList
:
ICollection
:
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.
Another difference in case of EF is that the IEnumerable is not executing the query to the DB untill you really enumerate the list. While the IList will execute the query and fetch the items in memory. 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. 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. Find more in this post: http://www.dailycode.info/BlogV2/post/entityframework-adding-ienumerable-to-cache
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With