• Stars
    star
    1,446
  • Rank 32,535 (Top 0.7 %)
  • Language
    C#
  • License
    Other
  • Created almost 6 years ago
  • Updated 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

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

EntityFramework.Exceptions

EntityFramework.Exceptions

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

License Target AppVeyor AppVeyor Coverage Status Ko-Fi

Maintainability Rating Vulnerabilities Bugs Code Smells Duplicated Lines (%) Coverage

Build Stats

Entity Framework Community Standup Live Show

Entity Framework Community Standup - Typed Exceptions for Entity Framework Core

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) such as UniqueConstraintException, CannotInsertNullException, MaxLengthExceededException, NumericOverflowException, ReferenceConstraintException you need.

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]}");
    }
}

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());

More Repositories

1

EFCore.Visualizer

Entity Framework Core queries debugger visualizer.
C#
419
star
2

LINQPad.QueryPlanVisualizer

SQL Server and PostgreSQL query execution plan visualizer for LINQPad
C#
399
star
3

DuckDB.NET

Bindings and ADO.NET Provider for DuckDB
C#
392
star
4

GraphQLinq

LINQ to GraphQL - Strongly typed GraphQL queries with LINQ query syntax. No more magic strings and runtime errors.
C#
202
star
5

Math-Expression-Evaluator

A C# library for parsing mathemitical expressions with support for parentheses and variables.
C#
114
star
6

BetterOpenWith

A better way to open files
Java
42
star
7

Dynamic-PInvoke

C#
15
star
8

Entity-Framework-Analyzers

Code Analyzers and Fixers for Common Entity Framework Issues.
C#
9
star
9

Maui-DotNetConf-Sample

Maui Spatial Data Sample App
C#
7
star
10

Dynamic-ViewState-in-ASP.Net-WebForms

A sample project showing how to access ViewState data dynamically by using DynamicObject class
ASP.NET
6
star
11

VpnProxyChanger

Automatically launches rdp to work PC and sets proxy
C#
4
star
12

EF-Core-Demos

EF Core Examples
C#
4
star
13

U2G-Shipping-Calculator

Google Chrome extension for calculating USA2Georgia shipping cost on amazon.com
JavaScript
4
star
14

Silverlight-Remote-Control

Silverlight 4 application with remote control support.
C#
3
star
15

Giorgi

3
star
16

TbilisiFloodDonations

Visualization of Tbilisi flood donations
HTML
3
star
17

Movie-Explorer

C#
2
star
18

userscripts

Collection of userscripts for different websites
2
star
19

SemanticKernel.Connectors.Oracle

Semantic Kernel memory built on top of Oracle 23ai
C#
2
star
20

Okta.CaloriesTracker

JavaScript
1
star
21

SE-Hot-Network-Questions-Filter

Greasemonkey & Tampermonkey script for filterting hot network questions on stackexchange sites
JavaScript
1
star
22

PostgresRangeTypes

Demo showing how to use PostgreSQL ranges from Entity Framework Core
C#
1
star
23

github-stats

Python
1
star
24

DuckDB.NET-Docs

DuckDB.NET project documentation.
C#
1
star
25

Semantic-Search-Demo

Demo app for pgvector semantic search
C#
1
star