Entity Framework Core vs. Dapper?
Do I use Dapper or Entity framework core for my next .NET project? It is always confusing when you have to make this decision and you need to make this decision right for the sake of the success of your project. Let me help you…
Introduction
An application that has been developed using .NET can be categorized as bad or good based on the Object-Relational Mapper (ORM) it has been using. Because choosing the right Object-Relational Mapper (ORM) can significantly impact the performance, maintainability, and scalability of your application. At the moment Entity Framework Core (EF Core) and Dapper are the two most popular choices among .NET developers. In this article, I am gonna talk about the differences between these two ORMs to help you make an informed decision for your next project.
Both Entity Framework Core (EF Core) and Dapper have the same fundamental purpose to simplify data access by abstracting away the complexities of database interactions and they are in different abstraction levels. However, they do so in different ways, each with its own strengths and weaknesses.
Importance of Choosing the Right ORM for a Project
Choosing the right ORM (Object-Relational Mapper) is important for the success of a project since it directly influences performance, developer productivity, maintainability, scalability, and control over database interactions. When we select a proper ORM for our project we need to consider factors such as performance requirements, project complexity, and the need for flexibility and control. By carefully evaluating these factors and choosing an ORM that aligns with the goals of the project and requirements, developers can ensure the efficiency, maintainability, and scalability of their applications.
What is EF Core?
Entity Framework Core is a modern and lightweight Object-Relational Mapping (ORM) framework developed by Microsoft for .NET applications. It allows developers to work with databases using .NET objects, abstracting much of the underlying database interactions. It provides a set of features that help us to work with databases, including change tracking, LINQ support, and database migrations.
EF Core is a feature-rich, extensible, and highly configurable framework that simplifies data access by abstracting away many of the complexities and working directly with databases, making it an excellent choice for projects with complex data models and relationships.
Here is the sample code for EF core.
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
namespace Test;
public class ApplicationDbContext : DbContext
{
public DbSet<Blog> User { get; set; }
public DbSet<Post> Department { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
}
}
public class User
{
public int UserId { get; set; }
public string FullName{ get; set; }
public int Age{ get; set; }
public int DepartmentId { get; set; }
public Department Department { get; set; }
}
public class Department
{
public int DepartmentId { get; set; }
public string Name { get; set; }
public List<User> Users { get; set; }
}
You have to make sure you have the connection string defined in your appsettings.json
or appsettings.{Environment}.json
file.
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=YourDB;Trusted_Connection=True;ConnectRetryCount=0"
}
}
Then after, in your application startup class (usually Startup.cs
), configure Entity Framework Core to use the connection string from your application settings and register ApplicationDbContext
with dependency injection.
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
namespace TestProject
{
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
// Configure DbContext with connection string from app settings
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}
}
}
An instance of these entity classes can be retrieved from the database with the use of the language Integrated Query (LINQ).
using (var db = new ApplicationDbContext())
{
var users = db.User
.Where(u => u.age > 20)
.OrderBy(u => u.FullName)
.ToList();
}
Data is created, deleted, and modified in the database using instances of your entity classes. This is how you can save data to the database.
using (var db = new ApplicationDbContext())
{
var department = new Department { Name = "TestDepartment" };
db.Department.Add(department);
db.SaveChanges();
}
What is Dapper?
Dapper is a lightweight, high-performance micro-ORM that is built for the .NET ecosystem. It was developed by the Stack Overflow team and it is more lightweight compared to EF Core. Dapper consists of helper functions for executing raw SQL queries, offering a performance-optimized, straightforward approach to data access. It focuses on simplicity and performance, offering direct mapping of SQL queries to .NET objects with minimal overhead. Dapper is well-suited for scenarios where raw performance is crucial, such as high-concurrency environments or applications with large datasets.
Here is the sample code for Dapper.
First defines the classes we need.
public class User
{
public int UserId { get; set; }
public string FullName{ get; set; }
public int Age{ get; set; }
public int DepartmentId { get; set; }
public Department Department { get; set; }
}
public class Department
{
public int DepartmentId { get; set; }
public string Name { get; set; }
public List<User> Users { get; set; }
}
This is how you can implement the CRUD operations.
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using Dapper;
public class UserRepository
{
private readonly SqlConnection _connection;
public UserRepository(SqlConnection connection)
{
_connection = connection ?? throw new ArgumentNullException(nameof(connection));
}
public void Insert(User user)
{
_connection.Execute("INSERT INTO Users (FullName, Age, DepartmentId) VALUES (@FullName, @Age, @DepartmentId)", user);
}
public User GetById(int userId)
{
return _connection.QueryFirstOrDefault<User>("SELECT * FROM Users WHERE UserId = @UserId", new { UserId = userId });
}
public void Update(User user)
{
_connection.Execute("UPDATE Users SET FullName = @FullName, Age = @Age, DepartmentId = @DepartmentId WHERE UserId = @UserId", user);
}
public void Delete(int userId)
{
_connection.Execute("DELETE FROM Users WHERE UserId = @UserId", new { UserId = userId });
}
}
Comparison Dapper VS Entity Framework
Ease of Use
EF Core allows developers to define database schema using C# classes and offers seamless integration with LINQ, making data queries more intuitive. It has built-in support for database migrations and schema management.
On the other hand with dapper, its requires writing raw SQL queries, which could be more intuitive for those familiar with SQL. Typically requires less boilerplate code for simple CRUD operations.
Performance
With EF core, the abstraction layer and additional features can introduce performance overhead. EF core offers lazy loading, which means it can be both an advantage and a drawback based on the use case. However, it provides cashing and other performance optimization features that make EF core faster sometimes.
Dapper is generally faster than EF Core and known for high-performance data access because it uses raw SQL queries. Here its minimal abstraction layer means less overhead.
Complexity
Dapper is designed to be simple and lightweight. It doesn’t abstract SQL queries or database operations as much as EF Core does, which means developers have more control over the SQL queries they write. This simplicity can lead to less complexity, especially for developers who are comfortable writing SQL.
Entity Framework Core abstracts away much of the database interaction, providing higher-level constructs like DbSet, LINQ queries, and automatic change tracking. This abstraction can lead to increased complexity in certain scenarios, especially when dealing with complex database schemas or performance tuning. However, it also offers productivity benefits, especially for developers who prefer working with objects rather than raw SQL.
Database support
Dapper supports a wide range of database providers including SQL Server, MySQL, PostgreSQL, SQLite, Oracle, etc. However, EF Core supports even more databases, including SQLite, Oracle, and IBM DB2.
Flexibility
EF core is highly configurable and extensible which means it allows for a wide range of customization and it has built-in support for multiple database providers. EF Core provides a more structured approach to data access that can make it easier to work with in larger projects.
However, Dapper provides more flexibility than EF Core because it allows you to execute raw SQL queries and map the results to .NET objects. It’s focused on one thing and does it well(data access). Since you write raw SQL, you have complete control over the queries.
Community and Support
Since EF core is a Microsoft product, it has a strong community and extensive documentation. We are getting regularly updated with new features and performance improvements.
For Dapper, it's smaller than EF Core, but the community is active and growing. Adequate documentation and there are plenty of third-party tutorials.
Advanced Features
EF core provides a set of advanced features such as automatically tracking changes to entities and updating them in the database, relationships, lazy loading, migrations, and query translation. It also has built-in support for managing complex relationships, transactions, and joins.
Dapper supports batch querying and multiple result sets. It's easy to call stored procedures and map results. It may have not advanced features provided by EF Core, such as automatic change tracking, lazy loading, and complex query translation since Dapper focuses on raw performance and simplicity. However, Dapper provides excellent support for executing raw SQL queries and mapping results to objects efficiently.
Additional Resources
Conclusion
In conclusion, when deciding between Dapper and Entity Framework Core for your .NET project, it’s essential to consider various factors such as ease of use, performance, complexity, database support, flexibility, community support, and advanced features.
Ultimately, the choice between Dapper and EF Core depends on your project requirements, team expertise, performance considerations, and preference for productivity versus control. Both frameworks have their strengths and weaknesses, so it’s essential to evaluate them based on your specific needs to make an informed decision for the success of your project.
See you in the next blog post. Bye Bye🍻🍸❤️❤️