EF ICollection Vs List Vs IEnumerable Vs IQueryable

Luis Valencia picture Luis Valencia · Jul 3, 2012 · Viewed 21.4k times · Source

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

Answer

Hans Kesting picture Hans Kesting · Jul 3, 2012

IQueryable:

  • Query isn't executed until you really iterate over the items, maybe by doing a .ToList() or a foreach. Which means you still can add filters, like a Where().
  • Extends IEnumerable

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).

IList:

  • 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

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.