renakre
renakre

Reputation: 8291

When is IEnumerable preferred over IQueryable in Entity Framework?

I understand how IEnumerable and IQueryable works. I just cannot imagine a situation where IEnumerable would be needed in entity framework when working with SQL database. I wonder if I can just discard IEnumerable in EF. Can you provide any useful example that shows IEnumerable could be more useful than IQueryable?

Upvotes: 0

Views: 130

Answers (2)

Dai
Dai

Reputation: 155648

Provided a data source (as IQueryable) can be queried, then yes, use IQueryable - though you shouldn't be creating IQueryable instances or implementing it yourself, that's what EF is for. You will still need to use IEnumerable as method parameters or return types if you're using EF with external data-sources or other data that isn't queryable itself, such as JOINing an EF table with non-EF data.

For example, you'd have a return type as IEnumerable<T> if the data you're returning isn't queryable because you called AsEnumerable or ToList but you don't want to reveal implementation details - but I'd then prefer IReadOnlyList<T> in that case.

Upvotes: 1

Enigmativity
Enigmativity

Reputation: 117175

There are three situations that come to mind.

  1. When EF cannot convert your query into a correct SQL statement - so you need to bring the results into memory to complete the computation.
  2. When you need to perform operations that involve operators that do not convert to SQL.
  3. When SQL server is slower at producing the computation than an in-memory calculation. Many times I have found that pulling all the data into memory is quicker than letting SQL to do it.

Upvotes: 1

Related Questions