#Common Performance Traps in Entity Framework

I recently read an article from SimpleTalk. It pretty much covered the common mistake and i am listing the one which i commonly do.

Bring only Columns you require,instead of All :

Lets assume we need only first name and last name from the table User  which holds information of user details (First Name, Last Name, Telephone No,Email Id,Location).

we need to write a query to bring all users whose location is  NewYork.

Most Common Query we write:


string Location= "NewYork"

var result= dbcontext.User.where(x=>x.Location==Location).ToList();

foreach(var usersinnewyork in result)

{

Console.WriteLine(usersinnewyork.FirstName);

Console.WriteLine(usersinnewyork.LastName);

}

In the above query the result brings all the columns while we need only first and last name.We might not be aware of impact of query we write,but identifying such queries in application would help us to avoid certain performance issues.

Modified Query with Anonymous Object :


string Location= "NewYork"

var result= dbcontext.User.where(x=>x.Location ==Location).Select( x=>new 

{
FirstName =x.FirstName,
LastName =x.LastName
});

In the above query we only bring what we need (first and last name).

 

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s