Why use AsQueryable() instead of List()? : C#

While using data access with the Entity Framework and LINQ, we always return List(), while some of developer prefer AsQueryable().

When we use AsQueryable, it just create a query, which is instruction to get a list. We can make further changes to the query later such as adding new Where clause that sent to the database level.

Returning IQueryable<T> has the advantage, that the execution is postponed until we start enumerating the result and we can compose the query with other queries and still get server side execution.

The problem is that when we cannot control the lifetime of the database context, we need an open context and must ensure that it stays open until the query gets executed. And then must ensure that the context will be disposed.

AsQueryable is an extension method for IEnumerable<T> that could do two things:

  • If the IEnumerable implements IQueryable just casts, doing nothing.
  • Otherwise creates a ‘fake’ IEnumerable<T> (EnumerableQuery<T>) that implements every method compiling the lambdas and calling to Enumerable extension methods.

So in most of the cases using AsQueryable is useless, unless u are forced to pass a IQueryable to a method and u have a IEnumerable instead, it’s a hack.

While using return List, we get an actual list with all the items in memory. If we add a new Where clause to it, we don’t get the fast filtering as the database provides. Instead we get all the information in the list and then filter out what we don’t need in the application.

Refrence

Why use AsQueryable() instead of List()

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s