Post navigation

Tips to improve Entity Framework Performance

Avoid to put all the DB Objects into One Single Entity Model

Entity Model specifies a single unit of work, not all our database. If we have many database objects that are not connected to one another or these(log tables, objects used by batch processes,etc.) are not used at all. Hence these objects are consuming space in the memory and cause performance degrades. So try to make separate entity models of related database objects.

Disable change tracking for entity if not needed

Whenever you retrieve the data only for reading purpose, not for modification then there is no need of object tracking. So disable object tracking by using MergeOption as below:

This option allow us to turn off the object cache and unnecessary identity management of the objects.

Use Pre-Generating Views to reduce response time for first request

When the object of ObjectContext is created first time in the application, the entity framework creates a set of classes that is 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 reduce this response time by creating view at compile time by using T4 template or EdmGen.exe command-line tool.

Avoid fetching all the fields if not required

Avoid fetching not required fields from the database. Suppose I have table of Customer with 20 fields and I am interested only in three fields – CustomerID, Name, Address then fetch only these three fields instead of fetching all the fields of the Customer table.

//Bad Practice

var customer =

(from cust in dataContext.Customers

select cust).ToList();

//Good Practice

var customer =

(from cust in dataContext.Customers

select new{

customer.CustomerID,

customer.Name,

customer.Address

}).ToList();

Choose appropriate Collection for data manipulation

In linq we have Var, IEnumerable, IQueryable, 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 difference among all these collection refer my articles IEnumerable VS IQueryable, IEnumerable VS IList andVar VS IEnumerable.

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 in first time but after that it boost the performance significantly. We use Compile method of CompiledQuery class for making compiled query.

Suppose you required to retrieve customers details again and again based on city then make this query to compiled query like as