Skip to content

Commit 6db8bf8

Browse files
Giorgiclaude
andcommitted
Add tests for TPH primary keys and foreign key name matching
Cover two cases the previous fixes changed but no test exercised: - A primary key violation in a TPH hierarchy whose key name does not contain the table name. Before keys were taken from GetDeclaredKeys, each entity type added its own entry, and PostgreSQL left the constraint details null. - A foreign key whose name contains another foreign key's name. Before the longest name was preferred, the first entry in model order won. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LUiK1q79vjmuEVjG6Pbbsa
1 parent 8e2bd06 commit 6db8bf8

2 files changed

Lines changed: 85 additions & 0 deletions

File tree

‎EntityFramework.Exceptions/Tests/DatabaseTests.cs‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,30 @@ public virtual async Task PrimaryKeyViolationThrowsUniqueConstraintException()
164164
}
165165
}
166166

167+
[Fact]
168+
public virtual async Task PrimaryKeyViolationInTphHierarchySetsConstraintDetails()
169+
{
170+
DemoContext.Vehicles.Add(new Car { Id = 1, Seats = 4 });
171+
DemoContext.SaveChanges();
172+
173+
CleanupContext();
174+
175+
DemoContext.Vehicles.Add(new Truck { Id = 1, Axles = 3 });
176+
var uniqueConstraintException = Assert.Throws<UniqueConstraintException>(() => DemoContext.SaveChanges());
177+
var asyncUniqueConstraintException = await Assert.ThrowsAsync<UniqueConstraintException>(() => DemoContext.SaveChangesAsync());
178+
179+
// MySQL always names the primary key PRIMARY, so it cannot be matched to the model.
180+
if (!isSqlite && !isMySql)
181+
{
182+
foreach (var exception in new[] { uniqueConstraintException, asyncUniqueConstraintException })
183+
{
184+
Assert.Equal("pk_fleet", exception.ConstraintName, ignoreCase: true);
185+
Assert.Equal([nameof(Vehicle.Id)], exception.ConstraintProperties);
186+
Assert.Equal(nameof(DemoContext.Vehicles), exception.SchemaQualifiedTableName);
187+
}
188+
}
189+
}
190+
167191
[Fact]
168192
public virtual async Task RequiredColumnViolationThrowsCannotInsertNullException()
169193
{
@@ -285,6 +309,30 @@ public virtual async Task ReferenceViolationThrowsReferenceConstraintException()
285309
}
286310
}
287311

312+
[Fact]
313+
public virtual async Task ReferenceViolationPicksLongestMatchingForeignKeyName()
314+
{
315+
var product = new Product { Name = "Ticket Product" };
316+
DemoContext.Products.Add(product);
317+
await DemoContext.SaveChangesAsync();
318+
319+
// FK_Tickets_Product_Spare contains FK_Tickets_Product, so both names appear in the error message.
320+
DemoContext.Tickets.Add(new Ticket { ProductId = product.Id, SpareProductId = 0 });
321+
322+
var referenceConstraintException = Assert.Throws<ReferenceConstraintException>(() => DemoContext.SaveChanges());
323+
var asyncReferenceConstraintException = await Assert.ThrowsAsync<ReferenceConstraintException>(() => DemoContext.SaveChangesAsync());
324+
325+
if (!isSqlite)
326+
{
327+
foreach (var exception in new[] { referenceConstraintException, asyncReferenceConstraintException })
328+
{
329+
Assert.Equal("FK_Tickets_Product_Spare", exception.ConstraintName, ignoreCase: true);
330+
Assert.Equal([nameof(Ticket.SpareProductId)], exception.ConstraintProperties);
331+
Assert.Equal(nameof(DemoContext.Tickets), exception.SchemaQualifiedTableName);
332+
}
333+
}
334+
}
335+
288336
[Fact]
289337
public virtual async Task ReferenceViolationThrowsReferenceConstraintExceptionThroughExecuteUpdate()
290338
{

‎EntityFramework.Exceptions/Tests/DemoContext.cs‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@ public class DemoContext : DbContext
1515
public DbSet<ProductReview> ProductReviews { get; set; }
1616
public DbSet<Employee> Employees { get; set; }
1717
public DbSet<Department> Departments { get; set; }
18+
public DbSet<Vehicle> Vehicles { get; set; }
19+
public DbSet<Ticket> Tickets { get; set; }
1820

1921
protected override void OnModelCreating(ModelBuilder builder)
2022
{
@@ -31,6 +33,19 @@ protected override void OnModelCreating(ModelBuilder builder)
3133
builder.Entity<Employee>().HasIndex(e => e.BadgeNumber).IsUnique();
3234

3335
builder.Entity<Department>().HasAlternateKey(d => d.Code);
36+
37+
// A TPH hierarchy shares one primary key. The key name deliberately does not contain the table name,
38+
// so a duplicate key entry per entity type could not be resolved from the table name in the message.
39+
builder.Entity<Vehicle>().HasKey(v => v.Id).HasName("pk_fleet");
40+
builder.Entity<Vehicle>().Property(v => v.Id).ValueGeneratedNever();
41+
builder.Entity<Car>();
42+
builder.Entity<Truck>();
43+
44+
// FK_Tickets_Product_Spare contains FK_Tickets_Product. NoAction avoids multiple cascade paths on SQL Server.
45+
builder.Entity<Ticket>().HasOne<Product>().WithMany().HasForeignKey(t => t.ProductId)
46+
.HasConstraintName("FK_Tickets_Product").OnDelete(DeleteBehavior.NoAction);
47+
builder.Entity<Ticket>().HasOne<Product>().WithMany().HasForeignKey(t => t.SpareProductId)
48+
.HasConstraintName("FK_Tickets_Product_Spare").OnDelete(DeleteBehavior.NoAction);
3449
}
3550

3651
public const int ProductNameMaxLength = 25;
@@ -81,6 +96,28 @@ public class Department
8196
public int Code { get; set; }
8297
}
8398

99+
public abstract class Vehicle
100+
{
101+
public int Id { get; set; }
102+
}
103+
104+
public class Car : Vehicle
105+
{
106+
public int Seats { get; set; }
107+
}
108+
109+
public class Truck : Vehicle
110+
{
111+
public int Axles { get; set; }
112+
}
113+
114+
public class Ticket
115+
{
116+
public int Id { get; set; }
117+
public int ProductId { get; set; }
118+
public int SpareProductId { get; set; }
119+
}
120+
84121
public class Customer
85122
{
86123
public int Id { get; set; }

0 commit comments

Comments
 (0)