As you know by default Entity framework is not giving Performance, Always we need to tune up as per our requirements. But there are a lot of things which must we need to keep in mind when we use EF.
- Disable change tracking for the entity if not needed: whenever you retrieve the data only for reading purposes, not for modification then there is no need for object tracking. So disabling object tracking by this option allows us to turn off the object cache and unnecessary identity management of the objects.
dbContext context = new dbContext() context.Country.MergeOption = MergeOption.NoTracking;
- Use Pre-Generating Views: to reduce response time for the first request when the object of ObjectContext is created the first time in the application, the entity framework creates a set of classes that are required to access the database. This set of classes is called view and if your data model is large then creating the view may delay the web application response to the first request for a page. We can download Entity Framework Power Tools.
- Choose appropriate Collection for data manipulation: In LINQ we have Var, IEnumerable, IQueryable, and IList type collection for data manipulation. Each collection has its importance and performance impact on the query, so beware of using all these Collection for data manipulation. For learning differences among all these Collection refer to my articles IEnumerable VS IQueryable IEnumerable VS IList and Var VS IEnumerable
- Avoid fetching all the fields if not required Avoid fetching not required fields from the database. Suppose I have a table of employees with 10 fields and I am interested only in three fields – id, Name, and Address then fetch only these three fields instead of fetching all the fields of the employee table.
- Retrieve the only required number of records: Must use skip and take for pagination in select query.
- Avoid using Contains: In LINQ, we use contains a method for checking existence. It is converted to “WHERE IN” in SQL which causes performance degradation.
- Use Compiled Query wherever needed: Make a query to compiled query if it is frequently used to fetch records from the database. This query is slow the first time but after that, it boosts the performance significantly. We use Compile method of CompiledQuery class for making the compiled queries.