Wednesday, November 28, 2012

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.

No comments:

Post a Comment