Strongly typed exceptions in EF Core

2025-07-20

.NET, EntityFramework, DB

If you've ever run into a DbUpdateException while using Entity Framework, you're not alone. This generic exception often leaves you digging through inner exceptions just to understand what went wrong. Whether it's a unique constraint violation or a null value in a non-nullable column, handling all these issues with one exception type is frustrating. Wouldn’t it be better if EF threw meaningful, strongly-typed exceptions instead?

Strongly Typed EF Exceptions

Thankfully, developer Giorgi Dalakishvili fixed this problem in his EntityFramework.Exceptions library. It provides strongly typed exceptions for common database errors, such as unique constraint violations, foreign key violations, and more. This allows you to handle specific exceptions in your code, providing better error handling and clearer logs. No more DbUpdateException with generic error messages!

After adding the library to your project, your EF code will throw descriptive exceptions like UniqueConstraintException, CannotInsertNullException and a few others, giving you the ability to catch them and handle them accordingly. Depending on your use case, you can return more detailed error message to the user performing the action or maybe retry the operation that would otherwise result in failure.

Example Usage

To use the library, you need to install the NuGet package EntityFramework.Exceptions, dedicated for your database provider. For SQL Server you can run the following command in your terminal, in the directory of project where you use Entity Framework:

1dotnet add package EntityFrameworkCore.Exceptions.SqlServer

For PostgreSQL, you would use:

1dotnet add package EntityFrameworkCore.Exceptions.PostgreSQL

All supported database providers are listed in the GitHub repository README page.

Once installed, you need to register the exception processor from the library in your DbContext class. This is done by overriding the OnConfiguring method and calling UseExceptionProcessor() on the DbContextOptionsBuilder. Here's an example:

1class ShopContext : DbContext
2{
3    public DbSet<Order> Orders { get; set; }
4    public DbSet<Products> Products { get; set; }
5
6    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
7    {
8        optionsBuilder.UseExceptionProcessor();
9    }
10}

And that's all. Simple and effective. No need for any additional configuration or setup. After this, you can start using the strongly typed exceptions in your code. Here's an example of how to handle a unique constraint violation:

1try
2{
3    using var context = new ShopContext();
4    var order = new Order { /* ... */ };
5    context.Orders.Add(order);
6    context.SaveChanges();
7}
8catch (UniqueConstraintException ex)
9{
10    // Handle unique constraint violation
11}
12catch (CannotInsertNullException ex)
13{
14    // Handle null value insertion in non-nullable column
15}

What's more, typed exceptions also provide additional properties that can be useful for logging or debugging. For example, UniqueConstraintException has a ConstraintName property that contains the name of the violated constraint, and CannotInsertNullException has a ColumnName property that indicates which column was attempted to be set to NULL. You can use these properties to provide more context in your logs or error messages.

1catch (UniqueConstraintException ex)
2{
3    logger.LogError($"Unique constraint violation: {ConstraintName}", ex.ConstraintName);
4}
5catch (CannotInsertNullException ex)
6{
7    logger.LogError($"Cannot insert null value into column {ColumnName}", ex.ColumnName);
8}

Entity Framework extensibility

While not everyone may need this library, maybe they don't need such granular error handling, it seems that the option to enable strongly typed exceptions in EF Core would be a great addition to the base framework. Possibly by setting a flag during DbContext configuration. It would allow developers to handle database errors more effectively and provide better user experience in their applications, if their use case requires it.

But even if it's not included out-of-the-box, it shows how extensible Entity Framework is. By just adding a single line of code to your DbContext, you can change the way exceptions are handled in your application. This is a great example of how EF Core can be extended to meet specific needs, and how the community can contribute to improving the framework.

For more insight into the library, I encourage you to check out Entity Framework Community Standup episode where Giorgi Dalakishvili explains the library and its features in detail. It's a great resource to understand how to use the library effectively and how it can improve your error handling in EF Core applications.