### Install MySQL Package Source: https://github.com/giorgi/entityframework.exceptions/blob/main/DbExceptionClassifier/README.md Install the MySQL-specific package for DbExceptionClassifier using the .NET CLI. ```bash dotnet add package DbExceptionClassifier.MySQL ``` -------------------------------- ### Install SQLite Package Source: https://github.com/giorgi/entityframework.exceptions/blob/main/DbExceptionClassifier/README.md Install the SQLite-specific package for DbExceptionClassifier using the .NET CLI. ```bash dotnet add package DbExceptionClassifier.Sqlite ``` -------------------------------- ### Install SQL Server Package Source: https://github.com/giorgi/entityframework.exceptions/blob/main/DbExceptionClassifier/README.md Install the SQL Server-specific package for DbExceptionClassifier using the .NET CLI. ```bash dotnet add package DbExceptionClassifier.SqlServer ``` -------------------------------- ### Install Oracle Package Source: https://github.com/giorgi/entityframework.exceptions/blob/main/DbExceptionClassifier/README.md Install the Oracle-specific package for DbExceptionClassifier using the .NET CLI. ```bash dotnet add package DbExceptionClassifier.Oracle ``` -------------------------------- ### Add EntityFrameworkCore.Exceptions.MySql Package Source: https://github.com/giorgi/entityframework.exceptions/blob/main/README.md Install the MySQL specific package for EntityFramework.Exceptions. ```bash dotnet add package EntityFrameworkCore.Exceptions.MySql ``` -------------------------------- ### Install MySQL Pomelo Package Source: https://github.com/giorgi/entityframework.exceptions/blob/main/DbExceptionClassifier/README.md Install the MySQL Pomelo-specific package for DbExceptionClassifier using the .NET CLI. ```bash dotnet add package DbExceptionClassifier.MySQL.Pomelo ``` -------------------------------- ### Add EntityFrameworkCore.Exceptions.PostgreSQL Package Source: https://github.com/giorgi/entityframework.exceptions/blob/main/README.md Install the PostgreSQL specific package for EntityFramework.Exceptions. ```bash dotnet add package EntityFrameworkCore.Exceptions.PostgreSQL ``` -------------------------------- ### Add EntityFrameworkCore.Exceptions.Sqlite Package Source: https://github.com/giorgi/entityframework.exceptions/blob/main/README.md Install the SQLite specific package for EntityFramework.Exceptions. ```bash dotnet add package EntityFrameworkCore.Exceptions.Sqlite ``` -------------------------------- ### Add EntityFrameworkCore.Exceptions.SqlServer Package Source: https://github.com/giorgi/entityframework.exceptions/blob/main/README.md Install the SQL Server specific package for EntityFramework.Exceptions. ```bash dotnet add package EntityFrameworkCore.Exceptions.SqlServer ``` -------------------------------- ### Add EntityFrameworkCore.Exceptions.Oracle Package Source: https://github.com/giorgi/entityframework.exceptions/blob/main/README.md Install the Oracle specific package for EntityFramework.Exceptions. ```bash dotnet add package EntityFrameworkCore.Exceptions.Oracle ``` -------------------------------- ### Add EntityFrameworkCore.Exceptions.MySql.Pomelo Package Source: https://github.com/giorgi/entityframework.exceptions/blob/main/README.md Install the Pomelo MySQL specific package for EntityFramework.Exceptions. ```bash dotnet add package EntityFrameworkCore.Exceptions.MySql.Pomelo ``` -------------------------------- ### Usage Example Source: https://github.com/giorgi/entityframework.exceptions/blob/main/DbExceptionClassifier/README.md Demonstrates how to use a specific classifier (e.g., PostgreSQLExceptionClassifier) within a try-catch block to handle database exceptions. ```APIDOC ## Usage Example ### Description This example shows how to catch and handle specific database exceptions using an instance of `PostgreSQLExceptionClassifier`. ### Code ```csharp var classifier = new PostgreSQLExceptionClassifier(); try { // Execute your ADO.NET command await command.ExecuteNonQueryAsync(); } catch (DbException ex) when (classifier.IsUniqueConstraintError(ex)) { // Handle unique constraint violation } catch (DbException ex) when (classifier.IsReferenceConstraintError(ex)) { // Handle foreign key violation } ``` ``` -------------------------------- ### Register Exception Processor with DbContext (SQLite) Source: https://context7.com/giorgi/entityframework.exceptions/llms.txt Configure your DbContext for SQLite by calling `UseExceptionProcessor()` after `UseSqlite()`. Ensure the `EntityFrameworkCore.Exceptions.Sqlite` package is installed. ```csharp // ── SQLite ─────────────────────────────────────────────────────────────────── // dotnet add package EntityFrameworkCore.Exceptions.Sqlite using EntityFramework.Exceptions.Sqlite; optionsBuilder .UseSqlite("Data Source=app.db") .UseExceptionProcessor(); ``` -------------------------------- ### Register Exception Processor with DbContext (PostgreSQL) Source: https://context7.com/giorgi/entityframework.exceptions/llms.txt Configure your DbContext for PostgreSQL by calling `UseExceptionProcessor()` after `UseNpgsql()`. Ensure the `EntityFrameworkCore.Exceptions.PostgreSQL` package is installed. ```csharp // ── PostgreSQL ─────────────────────────────────────────────────────────────── // dotnet add package EntityFrameworkCore.Exceptions.PostgreSQL using EntityFramework.Exceptions.PostgreSQL; optionsBuilder .UseNpgsql(connectionString) .UseExceptionProcessor(); ``` -------------------------------- ### Register Exception Processor with DbContext (Oracle) Source: https://context7.com/giorgi/entityframework.exceptions/llms.txt Configure your DbContext for Oracle by calling `UseExceptionProcessor()` after `UseOracle()`. Ensure the `EntityFrameworkCore.Exceptions.Oracle` package is installed. ```csharp // ── Oracle ──────────────────────────────────────────────────────────────────── // dotnet add package EntityFrameworkCore.Exceptions.Oracle using EntityFramework.Exceptions.Oracle; optionsBuilder .UseOracle(connectionString) .UseExceptionProcessor(); ``` -------------------------------- ### Add DbExceptionClassifier.PostgreSQL Package Source: https://github.com/giorgi/entityframework.exceptions/blob/main/README.md Install the PostgreSQL specific package for DbExceptionClassifier to classify ADO.NET database exceptions directly. ```bash dotnet add package DbExceptionClassifier.PostgreSQL ``` -------------------------------- ### Register Exception Processor with DbContext (MySQL Pomelo) Source: https://context7.com/giorgi/entityframework.exceptions/llms.txt Configure your DbContext for MySQL (Pomelo) by calling `UseExceptionProcessor()` after `UseMySql()`. Ensure the `EntityFrameworkCore.Exceptions.MySQL.Pomelo` package is installed. ```csharp // ── MySQL (Pomelo) ──────────────────────────────────────────────────────────── // dotnet add package EntityFrameworkCore.Exceptions.MySQL.Pomelo using EntityFramework.Exceptions.MySQL.Pomelo; optionsBuilder .UseMySql(connectionString, ServerVersion.AutoDetect(connectionString)) .UseExceptionProcessor(); ``` -------------------------------- ### Register Exception Processor with DbContext (SQL Server) Source: https://context7.com/giorgi/entityframework.exceptions/llms.txt Configure your DbContext to use the exception processor for SQL Server by calling `UseExceptionProcessor()` after `UseSqlServer()`. Ensure the `EntityFrameworkCore.Exceptions.SqlServer` package is installed. ```csharp // ── SQL Server ────────────────────────────────────────────────────────────── // dotnet add package EntityFrameworkCore.Exceptions.SqlServer using EntityFramework.Exceptions.SqlServer; using Microsoft.EntityFrameworkCore; public class AppDbContext : DbContext { public DbSet Products { get; set; } public DbSet ProductSales { get; set; } protected override void OnModelCreating(ModelBuilder builder) { builder.Entity().HasIndex(p => p.Name).IsUnique(); builder.Entity().Property(p => p.Name).IsRequired().HasMaxLength(25); builder.Entity().Property(s => s.Price).HasColumnType("decimal(5,2)").IsRequired(); } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder .UseSqlServer("Server=.;Database=Demo;Trusted_Connection=True;") .UseExceptionProcessor(); // ← single call enables typed exceptions } } ``` -------------------------------- ### Configure DbContext Pooling with UseExceptionProcessor Source: https://github.com/giorgi/entityframework.exceptions/blob/main/README.md When using DbContext pooling, add the UseExceptionProcessor extension method when configuring the DbContextPool. Replace UseNpgsql with the appropriate SQL flavor. ```csharp // Replace UseNpgsql with the sql flavor you're using builder.Services.AddDbContextPool(options => options .UseNpgsql(config.GetConnectionString("DemoConnection")) .UseExceptionProcessor()); ``` -------------------------------- ### Configure DbContext with UseExceptionProcessor Source: https://github.com/giorgi/entityframework.exceptions/blob/main/README.md Configure your DbContext to use the exception processor by calling UseExceptionProcessor in the OnConfiguring method. This enables specific exception handling for database errors. ```csharp class DemoContext : DbContext { public DbSet Products { get; set; } public DbSet ProductSale { get; set; } protected override void OnModelCreating(ModelBuilder builder) { builder.Entity().HasIndex(u => u.Name).IsUnique(); } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseExceptionProcessor(); } } ``` -------------------------------- ### DbContext Pooling with Exception Processor (DI Registration) Source: https://context7.com/giorgi/entityframework.exceptions/llms.txt When using `AddDbContextPool`, configure the exception processor within the options lambda passed to `AddDbContextPool`. This ensures typed exceptions are processed for pooled contexts. ```csharp using EntityFramework.Exceptions.PostgreSQL; var builder = WebApplication.CreateBuilder(args); builder.Services.AddDbContextPool(options => options .UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection")) .UseExceptionProcessor()); // works with pooled contexts ``` -------------------------------- ### Classify PostgreSQL Exception Source: https://github.com/giorgi/entityframework.exceptions/blob/main/DbExceptionClassifier/README.md Create a PostgreSQL classifier and use it within a catch block to identify unique constraint violations. ```csharp var classifier = new PostgreSQLExceptionClassifier(); try { // Execute your ADO.NET command await command.ExecuteNonQueryAsync(); } catch (DbException ex) when (classifier.IsUniqueConstraintError(ex)) { // Handle unique constraint violation } catch (DbException ex) when (classifier.IsReferenceConstraintError(ex)) { // Handle foreign key violation } ``` -------------------------------- ### IDbExceptionClassifier Interface Source: https://github.com/giorgi/entityframework.exceptions/blob/main/DbExceptionClassifier/README.md Defines methods for classifying various database exceptions. ```csharp public interface IDbExceptionClassifier { bool IsUniqueConstraintError(DbException exception); bool IsReferenceConstraintError(DbException exception); bool IsCannotInsertNullError(DbException exception); bool IsMaxLengthExceededError(DbException exception); bool IsNumericOverflowError(DbException exception); bool IsDeadlockError(DbException exception); } ``` -------------------------------- ### Handle ReferenceConstraintException for FK Violations Source: https://context7.com/giorgi/entityframework.exceptions/llms.txt Catch ReferenceConstraintException when inserting a record with a missing parent or deleting a parent with child records. Constraint details are populated for supported databases. ```csharp using EntityFramework.Exceptions.Common; await using var db = new AppDbContext(); // Insert with missing parent (ProductId = 0, no matching Product) db.ProductSales.Add(new ProductSale { Price = 9.99m }); try { await db.SaveChangesAsync(); } catch (ReferenceConstraintException ex) { Console.WriteLine($"FK Constraint : {ex.ConstraintName}"); // e.g. "FK_ProductSales_Products_ProductId" Console.WriteLine($"Properties : {string.Join(", ", ex.ConstraintProperties)}"); // e.g. "ProductId" Console.WriteLine($"Table : {ex.SchemaQualifiedTableName}"); } // Delete parent while children exist: var parent = await db.Products.FindAsync(1); db.Products.Remove(parent!); try { await db.SaveChangesAsync(); } catch (ReferenceConstraintException ex) { Console.WriteLine("Cannot delete parent — child records exist: " + ex.ConstraintName); } // Via ExecuteDeleteAsync: try { await db.Products .Where(p => p.Id == 1) .ExecuteDeleteAsync(); } catch (ReferenceConstraintException ex) { Console.WriteLine("Bulk delete blocked by foreign key: " + ex.ConstraintName); } ``` -------------------------------- ### Classify PostgreSQL DbExceptions with IDbExceptionClassifier Source: https://context7.com/giorgi/entityframework.exceptions/llms.txt Use PostgreSQLExceptionClassifier to identify specific constraint violations and errors in PostgreSQL. Ensure the DbExceptionClassifier.PostgreSQL package is added. ```csharp // dotnet add package DbExceptionClassifier.PostgreSQL // dotnet add package DbExceptionClassifier.SqlServer using DbExceptionClassifier.PostgreSQL; using DbExceptionClassifier.SqlServer; using System.Data.Common; // PostgreSQL classifier var pgClassifier = new PostgreSQLExceptionClassifier(); await using var conn = new Npgsql.NpgsqlConnection(connectionString); await conn.OpenAsync(); await using var cmd = conn.CreateCommand(); cmd.CommandText = "INSERT INTO products (name) VALUES (@name)"; cmd.Parameters.AddWithValue("name", "duplicate-value"); try { await cmd.ExecuteNonQueryAsync(); } catch (DbException ex) when (pgClassifier.IsUniqueConstraintError(ex)) { Console.WriteLine("Unique constraint violation (PostgreSQL)."); } catch (DbException ex) when (pgClassifier.IsReferenceConstraintError(ex)) { Console.WriteLine("Foreign key violation (PostgreSQL)."); } catch (DbException ex) when (pgClassifier.IsCannotInsertNullError(ex)) { Console.WriteLine("NOT NULL violation (PostgreSQL)."); } catch (DbException ex) when (pgClassifier.IsMaxLengthExceededError(ex)) { Console.WriteLine("String too long (PostgreSQL)."); } catch (DbException ex) when (pgClassifier.IsNumericOverflowError(ex)) { Console.WriteLine("Numeric overflow (PostgreSQL)."); } catch (DbException ex) when (pgClassifier.IsDeadlockError(ex)) { Console.WriteLine("Deadlock detected (PostgreSQL)."); } // SQL Server classifier var sqlClassifier = new SqlServerExceptionClassifier(); // — same pattern, different classifier instance ``` -------------------------------- ### Composite Exception Classifier Source: https://github.com/giorgi/entityframework.exceptions/blob/main/DbExceptionClassifier/README.md Combine multiple database classifiers into a single instance to handle exceptions from different database types. ```csharp var classifier = new CompositeExceptionClassifier( new PostgreSQLExceptionClassifier(), new SqlServerExceptionClassifier() ); try { await command.ExecuteNonQueryAsync(); } catch (DbException ex) when (classifier.IsUniqueConstraintError(ex)) { // Works regardless of which database threw the exception } ``` -------------------------------- ### Combine multiple IDbExceptionClassifier instances with CompositeExceptionClassifier Source: https://context7.com/giorgi/entityframework.exceptions/llms.txt Use CompositeExceptionClassifier to unify exception handling across different database providers like PostgreSQL and SQL Server. This is useful for multi-tenant applications. ```csharp using DbExceptionClassifier.Common; using DbExceptionClassifier.PostgreSQL; using DbExceptionClassifier.SqlServer; using System.Data.Common; // Combine classifiers for a multi-tenant app routing to PG and SQL Server var classifier = new CompositeExceptionClassifier( new PostgreSQLExceptionClassifier(), new SqlServerExceptionClassifier() ); try { await command.ExecuteNonQueryAsync(); // command targets either PG or SQL Server } catch (DbException ex) when (classifier.IsUniqueConstraintError(ex)) { // fires regardless of which provider threw Console.WriteLine("Unique constraint violated."); } catch (DbException ex) when (classifier.IsDeadlockError(ex)) { Console.WriteLine("Deadlock — retry the operation."); } // All six classification methods are available: bool isRef = classifier.IsReferenceConstraintError(ex); bool isNull = classifier.IsCannotInsertNullError(ex); bool isLength = classifier.IsMaxLengthExceededError(ex); bool isOverflow = classifier.IsNumericOverflowError(ex); bool isUnique = classifier.IsUniqueConstraintError(ex); bool isDeadlock = classifier.IsDeadlockError(ex); ``` -------------------------------- ### IDbExceptionClassifier Interface Source: https://github.com/giorgi/entityframework.exceptions/blob/main/DbExceptionClassifier/README.md The main interface for classifying database exceptions. Implementations provide methods to check for specific error types. ```APIDOC ## Interface: IDbExceptionClassifier ### Description Provides methods to classify `DbException` instances into common database error types. ### Methods - **IsUniqueConstraintError**(DbException exception): bool - Checks if the exception is a unique constraint violation. - **IsReferenceConstraintError**(DbException exception): bool - Checks if the exception is a foreign key constraint violation. - **IsCannotInsertNullError**(DbException exception): bool - Checks if the exception is a 'cannot insert null' error. - **IsMaxLengthExceededError**(DbException exception): bool - Checks if the exception is a 'max length exceeded' error. - **IsNumericOverflowError**(DbException exception): bool - Checks if the exception is a numeric overflow error. - **IsDeadlockError**(DbException exception): bool - Checks if the exception is a deadlock error. ``` -------------------------------- ### Handle UniqueConstraintException in EF Core Source: https://github.com/giorgi/entityframework.exceptions/blob/main/README.md Catch and handle UniqueConstraintException when a unique constraint is violated during SaveChanges. Access ConstraintName and ConstraintProperties for details. Ensure the index is defined in the EF Model for these properties to be populated. ```csharp 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]}"); } } ``` -------------------------------- ### CompositeExceptionClassifier Source: https://github.com/giorgi/entityframework.exceptions/blob/main/DbExceptionClassifier/README.md Allows combining multiple IDbExceptionClassifier instances to handle exceptions from different database types. ```APIDOC ## Class: CompositeExceptionClassifier ### Description Combines multiple `IDbExceptionClassifier` instances. It delegates the classification to each classifier and returns `true` if any of them match the exception. ### Constructor - **CompositeExceptionClassifier**(params IDbExceptionClassifier[] classifiers) ### Usage Example ```csharp var classifier = new CompositeExceptionClassifier( new PostgreSQLExceptionClassifier(), new SqlServerExceptionClassifier() ); try { await command.ExecuteNonQueryAsync(); } catch (DbException ex) when (classifier.IsUniqueConstraintError(ex)) { // Handles unique constraint violations from either PostgreSQL or SQL Server } ``` ``` -------------------------------- ### Handle NOT NULL Constraint Violation Source: https://context7.com/giorgi/entityframework.exceptions/llms.txt Catch `CannotInsertNullException` when a required column receives a null value during `SaveChanges` or `ExecuteUpdate`. The `InnerException` may contain provider-specific details. ```csharp using EntityFramework.Exceptions.Common; await using var db = new AppDbContext(); // Product.Name is required (HasMaxLength + IsRequired in model) db.Products.Add(new Product()); // Name is null try { await db.SaveChangesAsync(); } catch (CannotInsertNullException ex) { Console.WriteLine("A required column was left null."); Console.WriteLine("Inner provider exception: " + ex.InnerException?.Message); } // Also fires through ExecuteUpdate: db.Products.Add(new Product { Name = "TempProduct" }); await db.SaveChangesAsync(); try { await db.Products .Where(p => p.Name == "TempProduct") .ExecuteUpdateAsync(p => p.SetProperty(pp => pp.Name, (string)null)); } catch (CannotInsertNullException) { Console.WriteLine("Cannot set Name to null via bulk update."); } ``` -------------------------------- ### Handle Unique Constraint Error with DbExceptionClassifier Source: https://github.com/giorgi/entityframework.exceptions/blob/main/README.md Use PostgreSQLExceptionClassifier to check if a DbException is a unique constraint violation. This approach does not require Entity Framework Core. ```csharp var classifier = new PostgreSQLExceptionClassifier(); try { await command.ExecuteNonQueryAsync(); } catch (DbException ex) when (classifier.IsUniqueConstraintError(ex)) { // Handle unique constraint violation } ``` -------------------------------- ### Handle DeadlockException for Database Deadlocks Source: https://context7.com/giorgi/entityframework.exceptions/llms.txt Catch DeadlockException when concurrent transactions cause a database deadlock. The InnerException is null by design to prevent interference with EF Core's retry logic. ```csharp using EntityFramework.Exceptions.Common; using Microsoft.EntityFrameworkCore; await using var db1 = new AppDbContext(); await using var db2 = new AppDbContext(); // Seed data db1.Products.AddRange( new Product { Name = "Item A" }, new Product { Name = "Item B" } ); await db1.SaveChangesAsync(); var id1 = db1.Products.First(p => p.Name == "Item A").Id; var id2 = db1.Products.First(p => p.Name == "Item B").Id; await using var tx1 = await db1.Database.BeginTransactionAsync(); await using var tx2 = await db2.Database.BeginTransactionAsync(); // Each transaction locks one row, then tries to lock the other → deadlock await db1.Products.Where(p => p.Id == id1) .ExecuteUpdateAsync(p => p.SetProperty(pp => pp.Name, "Item A1")); await db2.Products.Where(p => p.Id == id2) .ExecuteUpdateAsync(p => p.SetProperty(pp => pp.Name, "Item B1")); try { await Task.WhenAll( db1.Products.Where(p => p.Id == id2) .ExecuteUpdateAsync(p => p.SetProperty(pp => pp.Name, "Item B2")), db2.Products.Where(p => p.Id == id1) .ExecuteUpdateAsync(p => p.SetProperty(pp => pp.Name, "Item A2")) ); } catch (DeadlockException ex) { Console.WriteLine("Deadlock detected: " + ex.Message); // InnerException is null by design (avoids EF Core execution strategy interference) Console.WriteLine("InnerException: " + ex.InnerException); // null } ``` -------------------------------- ### Handle Numeric Overflow Exception Source: https://context7.com/giorgi/entityframework.exceptions/llms.txt Catch `NumericOverflowException` when a numeric value exceeds the precision or scale defined for a column. This exception can be triggered by `SaveChangesAsync` or `ExecuteUpdateAsync`. ```csharp using EntityFramework.Exceptions.Common; await using var db = new AppDbContext(); var product = new Product { Name = "Pi Product" }; db.Products.Add(product); // Price column is decimal(5,2) — value has too many significant digits db.ProductSales.Add(new ProductSale { Price = 3141.59265m, Product = product }); try { await db.SaveChangesAsync(); } catch (NumericOverflowException ex) { Console.WriteLine("Numeric value out of range for the column definition."); } // Also fires through ExecuteUpdateAsync: var sale = new ProductSale { Price = 1.00m, Product = product }; db.ProductSales.Add(sale); await db.SaveChangesAsync(); try { await db.ProductSales .Where(s => s.Id == sale.Id) .ExecuteUpdateAsync(s => s.SetProperty(ss => ss.Price, 3141.59265m)); } catch (NumericOverflowException) { Console.WriteLine("Bulk update caused numeric overflow."); } ``` -------------------------------- ### Handle Max Length Exceeded Exception Source: https://context7.com/giorgi/entityframework.exceptions/llms.txt Catch `MaxLengthExceededException` when a value exceeds the maximum length defined for a column. This applies to both `SaveChangesAsync` and `ExecuteUpdateAsync` operations. The `InnerException` can provide more details. ```csharp using EntityFramework.Exceptions.Common; await using var db = new AppDbContext(); // ProductNameMaxLength = 25 in the model db.Products.Add(new Product { Name = new string('X', 30) }); try { await db.SaveChangesAsync(); } catch (MaxLengthExceededException ex) { Console.WriteLine("Value too long for the column."); Console.WriteLine("Inner exception: " + ex.InnerException?.Message); } // Also works via ExecuteUpdateAsync: db.Products.Add(new Product { Name = "Short" }); await db.SaveChangesAsync(); try { await db.Products .Where(p => p.Name == "Short") .ExecuteUpdateAsync(p => p.SetProperty(pp => pp.Name, new string('X', 30))); } catch (MaxLengthExceededException) { Console.WriteLine("Bulk update exceeded max column length."); } ``` -------------------------------- ### Handle Unique Constraint Violation Source: https://context7.com/giorgi/entityframework.exceptions/llms.txt Catch `UniqueConstraintException` when `SaveChanges` or `ExecuteUpdate` violates a unique index or primary key. Properties like `ConstraintName`, `ConstraintProperties`, and `SchemaQualifiedTableName` are populated if the index is defined in the EF Core model. ```csharp using EntityFramework.Exceptions.Common; await using var db = new AppDbContext(); db.Products.Add(new Product { Name = "Widget" }); db.Products.Add(new Product { Name = "Widget" }); // duplicate — triggers unique constraint try { await db.SaveChangesAsync(); } catch (UniqueConstraintException ex) { Console.WriteLine($"Constraint : {ex.ConstraintName}"); // e.g. "IX_Products_Name" Console.WriteLine($"Properties : {string.Join(", ", ex.ConstraintProperties)}"); // e.g. "Name" Console.WriteLine($"Table : {ex.SchemaQualifiedTableName}"); // e.g. "Products" Console.WriteLine($"Entries : {ex.Entries.Count}"); // number of EF entity entries involved } // Also fires through ExecuteUpdate / ExecuteUpdateAsync: try { await db.Products .ExecuteUpdateAsync(p => p.SetProperty(pp => pp.Name, "Widget")); // all rows → same name } catch (UniqueConstraintException ex) { Console.WriteLine("Bulk update violated unique constraint: " + ex.ConstraintName); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.