Posted by: bibhaspaul | November 28, 2012

Entity framework and data iteration


Entity framework and data iteration

We can write following piece of code to retrieve all records using DBSet. If we look at the database pro-filer we could see “SELECT * FROM Category” statement issued in the database.

var dbContext = new NorthwindEntities()

foreach (Category cat in dbContext.Categories)
{
Console.WriteLine(cat.CategoryName);
}

Some time we may need to iterate the same set of result set multiple times in a logical unit like below.

private void LogicalUnit()
{
var dbContext = new NorthwindEntities()
foreach (Category cat in dbContext.Categories)
{
Console.WriteLine(cat.CategoryName);
}

foreach (Category cat in dbContext.Categories)
{
Console.WriteLine(cat.CategoryName);
}

}

Apparently everything looks fine but I wondered when I looked into the pro-filer and saw above SQL statement issued twice.

To avoid this, we can perform LINQ operation such as ToList() to copy the result set into a list and iterate the list whenever required.

var categories = dbContext.Categories.ToList();

foreach (Category cat in categories)
{
Console.WriteLine(cat.CategoryName);
}

foreach (Category cat in categories)
{
Console.WriteLine(cat.CategoryName);
}

This will hit the database only once to execute the query. We can refer the local result set for further reference. This way we can bring down the repeated database hit.

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

Categories

%d bloggers like this: