using System; using System.Linq; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; await using var connection = new SqliteConnection("Data Source=:memory:;Foreign Keys=True"); await connection.OpenAsync(); var options = new DbContextOptionsBuilder().UseSqlite(connection).Options; await using (var db = new LabDb(options)) { await db.Database.EnsureCreatedAsync(); db.Items.Add(new Item { Name = "Original", Sku = "R1" }); await db.SaveChangesAsync(); } bool duplicate = false; await using (var db = new LabDb(options)) { db.Items.Add(new Item { Name = "Duplicate", Sku = "R1" }); try { await db.SaveChangesAsync(); } catch (DbUpdateException ex) when (ex.InnerException is SqliteException { SqliteErrorCode: 19, SqliteExtendedErrorCode: 2067 }) { duplicate = true; } } await using (var verify = new LabDb(options)) { Check(duplicate && await verify.Items.CountAsync() == 1 && (await verify.Items.SingleAsync()).Name == "Original", "unique index preserves original"); } Console.WriteLine("unique:rejected"); Console.WriteLine("rows:1"); static void Check(bool condition, string name) { if (!condition) throw new InvalidOperationException("CHECK: " + name); }