Sunday, September 29, 2024

Which .NET ORM - Dapper or Entity Framework?

Within the .NET ecosystem, two ORMs dominate, the lightweight Dapper (open source) and the fully featured Entity Framework (EF) by Microsoft. 

Depending on your project's size and requirements, either of these should work well for you, but there are definitely some known cases where each is a better fit. That's what we're discussing in this post.

When to use Dapper?

  • Small to medium size projects. It has low overhead in terms of setup and configuration.
  • The database tables are in place already and you're calling existing stored procedures. This is known as a data first approach.
  • You prefer to hand code the SQL for speed, optimization or fine tuning.

When to use Entity Framework?

  • Its a large and/or enterprise type project.
  • The database hasn't been created yet and you'd like to use a code first approach. The framework will create the database for you after you code the data models.
  • You want the ORM to handle transactions for you in the background.
  • You need to use the power of C# LINQ (Language Integrated Query), whereby SQL joins and other queries are generated for you based on your C# code.

Other important factors

  • Is your project likely to change frameworks, or need to be adapted to other databases? If yes I'd favour Dapper, because there's just less to migrate and configure. Dapper tries to not get in the way. There are no  additional abstractions and class models that happens with EF.
  • Are you using .NET Core? Its probably a controversial opinion but I feel that .NET Core as a framework is still quite unstable compared to the original .NET Framework. So when a new version comes out, there's normally breaking changes within EF Core. For that reason I'd also favour Dapper over EF for .NET Core projects.

What's not a factor?

  • Speed and performance. There's no longer any significant performance difference between Dapper and EF. Issues with performance are more likely to be something else that's not being done correctly at the SQL level, such as a lack of indexing, or an incorrect query.
  • The origin of the framework. The first release EF for .NET which came out in the 2000s had terrible performance. Since that time, all the performance issues have been fixed.