Closed mitselplik closed 2 years ago
.HasForeignKey(d => new { d.Year, d.PropertyId, d.ExemptionCode })
.HasPrincipalKey(d => new { d.PropertyExemptionId })
is incorrect. Referential integrity constraint in database requires that referencing properties and referenced properties should be matching in count to propagate values.
the child table has a foreign key constraint to the unique key constraint rather than the primary key constraint.
HasPrincipalKey should refer to unique key constraint rather than PK constraint. Change your code to following in relevant place.
builder.Entity<PropertyExemptionTaxingAuthorityValue>
.HasOne(d => d.PropertyExemption)
.WithMany(p => p.PropertyExemptionTaxingAuthorityValue)
.HasForeignKey(d => new { d.Year, d.PropertyId, d.ExemptionCode })
.HasPrincipalKey(c => new { c.Year, c.PropertyId, c.ExemptionCode })
.HasConstraintName("CFK_property_exemption_taxing_authority_value_property_exemption");
Apologies - I misunderstood the documentation. It is working now.
An error occurs if trying to model against an existing database where the parent table has both an int Id primary key plus a composite unique key consisting of other columns, and the child table has a foreign key constraint to the unique key constraint rather than the primary key constraint.
Many legacy databases are likely to have similar issues, where having an Id identity column makes data easy to track for CRUD operations, but a composite list of column values defines a unique constraint used elsewhere in the database.
For example, we have a class that mirrors an existing parent database table:
We have a related class that mirrors an existing child database table that has a foreign key constraint to the parent table's unique constraint rather than to the primary key:
The relevant portions of the model builder code are setup like so:
The above setup causes the following error to occur:
Further technical details
EF Core version: 3.1.3 Database provider: Microsoft.EntityFrameworkCore.SqlServer Target framework: .NET Core 3.1 Operating system: Windows 10 IDE: Visual Studio 2019 16.5.4 Community Edition Stack Trace: