a blog for those who code

Saturday, 8 April 2017

Top 4 Optimization tips in Entity Framework for Dot Net Applications

In this post we will be discussing about top 4 optimization tips in Entity Framework for Dot Net applications. Entity Framework is Microsoft's recommended data access technologies for new applications and now if you are not familiar with optimization technique in EF you miss to take the full advantage of Entity Framework.

1. Use AsNoTracking()

Sometimes you just want to read results from the database and do not want to change anything on it, then AsNoTracking will come handy because No-Tracking queries will tell Entity Framework that it should not track the results of a query thus EF will not performs any additional processing or storage of the entities. Using this approach EF will save a lot of time and thus your query is optimized.

//Usage
var user = dbContext.Users.AsNoTracking()
   .Where(user => user.UserId == userid)
   .SingleOrDefault();
return user;

2. Load Only Required Data

One thing which is seen by most of the developers is that they load all the data whether its a parent entity or child entity which will increase the load to the server. Instead they need to load only the required fields whenever possible. The below code is the optimized code where we will only need name of the user so we are selecting only that and not the whole entity.

//Usage
var user = dbContext.Users.AsNoTracking()
   .Where(user => user.UserId == userid)
   .Select(user => user.FullName )
   .SingleOrDefault();
return user;

3. Execute queries in Database and not in memory

Whenever possible try to execute the queries in database and not in the memory. Lets suppose we need to count the number of user whose first-name is Sachin so we need the below query which is an optimized query and will execute the query in database and not in memory.

//Usage
var user = dbContext.Users.Count(user => user.FirstName == "Sachin");

4. Use Early Loading to load Child Entities

When you know that you will be required with the child entities in future along with the parent entities you should early load the child entities instead of lazy loading. You should do that because in lazy loading it will fire a lot of queries when you will work with Child Entities whereas in Eager Loading you just need to fire single query.

//Usage
var user = dbContext.Users.Include(a=>a.UserDetails)
   .Where(user => user.UserId == userid)
   .SingleOrDefault();
return user;

Please Like and Share CodingDefined.com blog, if you find it interesting and helpful.

No comments:

Post a Comment