Linq: Deferred Execution

Linq queries are build as you call linq methods but they are not executed until you use the collection.

For example:

var result = new int[] { 1, 2, 3, 4, 5 }.Where(n => n > 2);

result does not yet contain the resulting values. But if you iterate through it:

foreach (var item in result)
{
}

It will run the query and return the resulting values.

There are other ways to run it, you could call ToList(), ToDictionary(), Count()

This feature allows you to only query when really needed so it won’t consume any unnecessary resources.

You just have to be careful when dealing with database. If you defer the execution of a query but then dispose of the DbContext you are going to get an exception. Because the framework can’t run your query on a disposed connection. For example:

IEnumerable<Person> people;

using (var db = new ApplicationDbContext())
{
    people = db.People;
}

// exception!
foreach (var item in people)
{
}

Instead what you have to do is:

IEnumerable<Person> people;

using (var db = new ApplicationDbContext())
{
    people = db.People.ToList(); // causes query execution
}

// ok
foreach (var item in people)
{
}
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