|
| 1 | +using Microsoft.EntityFrameworkCore; |
| 2 | + |
| 3 | +namespace SqlServerSimulator; |
| 4 | + |
| 5 | +/// <summary> |
| 6 | +/// Exercises the simulator's PRIMARY KEY constraint enforcement through EF |
| 7 | +/// Core. The duplicate-key path surfaces as <see cref="DbUpdateException"/> |
| 8 | +/// whose inner is the simulator's Msg 2627 — the same shape EF Core's |
| 9 | +/// SqlServer provider produces against a real database. |
| 10 | +/// </summary> |
| 11 | +[TestClass] |
| 12 | +public class EFCorePrimaryKey |
| 13 | +{ |
| 14 | + public TestContext TestContext { get; set; } = null!; |
| 15 | + |
| 16 | + [TestMethod] |
| 17 | + public void SaveChanges_FirstRow_RoundTripsThroughPrimaryKey() |
| 18 | + { |
| 19 | + using var context = new TestDbContext(TestDbContext.CreateInventorySimulation()); |
| 20 | + |
| 21 | + _ = context.Inventory.Add(new Inventory { Sku = "WIDGET-A", Quantity = 7 }); |
| 22 | + _ = context.SaveChanges(); |
| 23 | + |
| 24 | + var fetched = context.Inventory.AsNoTracking().Single(); |
| 25 | + Assert.AreEqual("WIDGET-A", fetched.Sku); |
| 26 | + Assert.AreEqual(7, fetched.Quantity); |
| 27 | + } |
| 28 | + |
| 29 | + [TestMethod] |
| 30 | + public void SaveChanges_DuplicateKey_RaisesDbUpdateException() |
| 31 | + { |
| 32 | + using var context = new TestDbContext(TestDbContext.CreateInventorySimulation()); |
| 33 | + |
| 34 | + _ = context.Inventory.Add(new Inventory { Sku = "WIDGET-A", Quantity = 1 }); |
| 35 | + _ = context.SaveChanges(); |
| 36 | + |
| 37 | + using var context2 = new TestDbContext(context.Simulation); |
| 38 | + _ = context2.Inventory.Add(new Inventory { Sku = "WIDGET-A", Quantity = 99 }); |
| 39 | + var ex = Assert.Throws<DbUpdateException>(() => context2.SaveChanges()); |
| 40 | + Assert.IsNotNull(ex.InnerException); |
| 41 | + Assert.Contains("PRIMARY KEY constraint 'pk_inventory'", ex.InnerException.Message); |
| 42 | + Assert.Contains("WIDGET-A", ex.InnerException.Message); |
| 43 | + } |
| 44 | + |
| 45 | + [TestMethod] |
| 46 | + public async Task SaveChangesAsync_DuplicateKey_RaisesDbUpdateException() |
| 47 | + { |
| 48 | + await using var context = new TestDbContext(TestDbContext.CreateInventorySimulation()); |
| 49 | + |
| 50 | + _ = context.Inventory.Add(new Inventory { Sku = "BOLT-7", Quantity = 1 }); |
| 51 | + _ = await context.SaveChangesAsync(this.TestContext.CancellationToken); |
| 52 | + |
| 53 | + await using var context2 = new TestDbContext(context.Simulation); |
| 54 | + _ = context2.Inventory.Add(new Inventory { Sku = "BOLT-7", Quantity = 2 }); |
| 55 | + var ex = await Assert.ThrowsAsync<DbUpdateException>(() => context2.SaveChangesAsync(this.TestContext.CancellationToken)); |
| 56 | + Assert.IsNotNull(ex.InnerException); |
| 57 | + Assert.Contains("PRIMARY KEY constraint 'pk_inventory'", ex.InnerException.Message); |
| 58 | + } |
| 59 | +} |
0 commit comments