Rules to Better Entity Framework

Optimize your use of Entity Framework by following best practices that enhance performance and maintainability. These guidelines cover everything from efficient querying and data manipulation to leveraging migrations and in-memory providers, ensuring your application runs smoothly and effectively.

  1. Entity Framework allows you to provide a strongly typed object framework (ORM) over your database. This helps abstract the database away allowing it to be replaced with other technologies as needed.

  2. It's expensive retrieving data from a database, as such it's important to only ask for the rows you require when getting data.

  3. When you cast IQueryable to IEnumerable and then query the data from there, Entity Framework must collect the data at the point you do the cast. This can result in very significant extra database load, and extra processing on the client side.

    NOTE: Using .AsEnumerable() achieves the same effect.

  4. One of EF Core's best features is the fact it tracks any changes you make to entities after you retrieve them. However this comes with a cost, if the data is only being read and the returned entities will never be modified then you can use the AsNoTracking method to inform EF Core not to bother tracking changes.

    This results in fairly significant memory and CPU improvements on the client side.

  5. When retrieving data it's much more efficient to only collect the data you need. It saves computation and IO on the database and also saves memory and CPU on the calling side.

  6. The Update method on an entity in EF Core marks all of its fields as dirty. This will result in all the fields being written back to the database.

  7. Often developers will include all the related entities in a query to help with debugging. Always remember to take these out. They cause excessive database load.

  8. Pagination can be expensive if all the pages are retrieved from the database before grabbing the relevant page. It's much more efficient to get only the page number requested back from the database.

  9. TagWith adds comments to the generated SQL. This makes it easier to identify queries when they run on the database.

  10. To avoid embarrassing failures in Production, it is important to ensure that your development systems are as similar as possible to what's expected in Production.

per page
1 - 10 of 17 items
We open source.Loving SSW Rules? Star us on GitHub. Star