Strongly typed exceptions for Entity Framework Core. Supports SQLServer, PostgreSQL, SQLite, Oracle and MySql.

entity-framework-corenetcore2sql-serverpostgresqlmysqlnetcore3database-exceptionssqlitesqlite3entityframeworkentity-frameworkodp-net
Star 增长趋势
Star
1.7k
Forks
83
周增长
+1
Issues
2
5001k1.5k
2018年12月2021年7月2024年2月2026年9月
README

EntityFramework.Exceptions

EntityFramework.Exceptions

Handle database errors easily when working with Entity Framework Core and ADO.NET. Supports SQLServer, PostgreSQL, SQLite, Oracle and MySql

License Target GitHub Actions Workflow Status Coverage Status Ko-Fi

Entity Framework Community Standup Live Show

Entity Framework Community Standup - Typed Exceptions for Entity Framework Core

OSS Power-Ups: EntityFramework.Exceptions

OSS Power-Ups: EntityFramework.Exceptions

Nick Chapsas - The Smart Way to Handle EF Core Exceptions

Nick Chapsas - The Smart Way to Handle EF Core Exceptions

Sponsors

A huge thanks to everyone (individuals or organisations) who have sponsored EntityFramework.Exceptions, but a massive thanks in particular to

Entity Framework Extensions - Sponsor

Dapper Plus - Sponsor

What does EntityFramework.Exceptions do?

When using Entity Framework Core for data access all database exceptions are wrapped in DbUpdateException. If you need to find whether the exception was caused by a unique constraint, value being too long or value missing for a required column you need to dig into the concrete DbException subclass instance and check the error code to determine the exact cause.

EntityFramework.Exceptions simplifies this by handling all the database specific details and throwing different exceptions. All you have to do is to configure DbContext by calling UseExceptionProcessor and handle the exception(s) you need, such as UniqueConstraintException, CannotInsertNullException, MaxLengthExceededException, NumericOverflowException, ReferenceConstraintException, or DeadlockException.

In case of UniqueConstraintException and ReferenceConstraintException you can get the name of the associated constraint with ConstraintName property. The ConstraintProperties will contain the properties that are part of the constraint.

[!WARNING] ConstraintName and ConstraintProperties will be populated only if the index is defined in the Entity Framework Model. These properties will not be populated if the index exists in the database but isn't part of the model or if the index is added with MigrationBuilder.Sql method.

[!WARNING] ConstraintName and ConstraintProperties will not be populated when using SQLite.

All these exceptions inherit from DbUpdateException for backwards compatibility.

How do I get started?

First, install the package corresponding to your database:

dotnet add package EntityFrameworkCore.Exceptions.SqlServer
dotnet add package EntityFrameworkCore.Exceptions.MySql
dotnet add package EntityFrameworkCore.Exceptions.MySql.Pomelo
dotnet add package EntityFrameworkCore.Exceptions.PostgreSQL
dotnet add package EntityFrameworkCore.Exceptions.Sqlite
dotnet add package EntityFrameworkCore.Exceptions.Oracle

Next, in your DbContext OnConfiguring method call UseExceptionProcessor extension method:

class DemoContext : DbContext
{
    public DbSet<Product> Products { get; set; }
    public DbSet<ProductSale> ProductSale { get; set; }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        builder.Entity<Product>().HasIndex(u => u.Name).IsUnique();
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseExceptionProcessor();
    }
}

You will now start getting different exception for different database error. For example, when a unique constraints fails you will get UniqueConstraintException exception:

using (var demoContext = new DemoContext())
{
    demoContext.Products.Add(new Product
    {
        Name = "demo",
        Price = 10
    });

    demoContext.Products.Add(new Product
    {
        Name = "demo",
        Price = 100
    });

    try
    {
        demoContext.SaveChanges();
    }
    catch (UniqueConstraintException e)
    {
        //Handle exception here
        Console.WriteLine($"Unique constraint {e.ConstraintName} violated. Duplicate value for {e.ConstraintProperties[0]}");
    }
}

[!TIP] If you want to use another native SQLite binary instead of e_sqlite3.dll use the EntityFrameworkCore.Exceptions.Sqlite.Core package. This package depends on Microsoft.Data.Sqlite.Core package, which doesn't include SQLite native binary so you can use any native binary you want.

Usage with DbContext pooling

Instead of calling UseExceptionProcessor in the OnConfiguring method, add it where you add your DbContextPool:

// Replace UseNpgsql with the sql flavor you're using
builder.Services.AddDbContextPool<DemoContext>(options => options
    .UseNpgsql(config.GetConnectionString("DemoConnection"))
    .UseExceptionProcessor());

DbExceptionClassifier

If you don't use Entity Framework Core, you can use the DbExceptionClassifier packages to classify ADO.NET database exceptions directly. They provide a unified IDbExceptionClassifier interface without any EF Core dependency.

dotnet add package DbExceptionClassifier.PostgreSQL
var classifier = new PostgreSQLExceptionClassifier();

try
{
    await command.ExecuteNonQueryAsync();
}
catch (DbException ex) when (classifier.IsUniqueConstraintError(ex))
{
    // Handle unique constraint violation
}

See the DbExceptionClassifier README for full documentation.

相关仓库
kgrzybek/modular-monolith-with-ddd

Full Modular Monolith application with Domain-Driven Design approach.

C#MIT Licensedddddd-architecture
14k2.2k
jasontaylordev/NorthwindTraders

Northwind Traders is a sample application built using ASP.NET Core and Entity Framework Core.

C#appMIT Licenseentity-framework-corenorthwind-database
5k1.6k
simplcommerce/SimplCommerce

A simple, cross platform, modulith ecommerce system built on .NET

C#appApache License 2.0modularecommerce
simplcommerce.com
4.4k1.7k
ivanpaulovich/clean-architecture-manga

:cyclone: Clean Architecture with .NET6, C#10 and React+Redux. Use cases as central organizing structure, completely testable, decoupled from frameworks

C#tutorialApache License 2.0solid-principlesddd-architecture
paulovich.net
4.4k752
borisdj/EFCore.BulkExtensions

Entity Framework EF Core efcore Bulk Batch Extensions with BulkCopy in .Net for Insert Update Delete Read (CRUD), Truncate and SaveChanges operations on SQL Server, PostgreSQL, MySQL, SQLite, Oracle

C#libraryOtherentity-framework-coreentityframeworkcore
codis.tech/efcorebulk
4k637
kgrzybek/sample-dotnet-core-cqrs-api

Sample .NET Core REST API CQRS implementation with raw SQL and DDD using Clean Architecture.

C#tutorialMIT Licensedddddd-example
kamilgrzybek.com/design/simple-cqrs-implementation-with-raw-sql-and-ddd/
3.1k678
PomeloFoundation/Pomelo.EntityFrameworkCore.MySql

Entity Framework Core provider for MySQL and MariaDB built on top of MySqlConnector

C#MIT Licenseentity-frameworkdotnet
3k417
ErikEJ/EFCorePowerTools

Entity Framework Core Power Tools - reverse engineering, migrations and model visualization in Visual Studio & CLI

C#MIT Licenseentity-framework-corevisual-studio
2.5k335
zzzprojects/EntityFramework-Plus

Entity Framework Plus extends your DbContext with must-haves features: Include Filter, Auditing, Caching, Query Future, Batch Delete, Batch Update, and more

C#libraryMIT Licensecsharpdotnet
entityframework-plus.net
2.3k319
realworld-apps/aspnetcore-realworld-example-app

ASP.NET Core backend implementation for RealWorld

C#MIT Licenseasp-net-corenet-core
realworld.io
2.1k634
npgsql/efcore.pg

Entity Framework Core provider for PostgreSQL

C#PostgreSQL Licenseentity-frameworknpgsql
1.8k263
dotnet/EntityFramework.Docs

Documentation for Entity Framework Core and Entity Framework 6

MermaidtutorialCreative Commons Attribution 4.0 Internationaldocumentationorm
learn.microsoft.com/ef/
1.7k2k