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 DataOne 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 memoryWhenever 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 EntitiesWhen 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.