Reputation: 2029
I am trying to apply a unique composite constraint, one of the parts of the constraint is a foreign key. The only way I can seem to make it work is to explicitly defined the foreign key in my domain class, which I want to avoid. Is this possible?
The problem and the workaround applies to both HasAlternateKey
and HasIndex
. The solution builds fine, but the constraint is ignored when creating a migration until the shadow property is turned into a real property in the domain class.
This does NOT work (migration ignores this):
entity.HasAlternateKey(e => new { e.Header.Id, e.Version, e.StartDate });
This does work AFTER turning shadow property HeaderID into a real one:
entity.HasAlternateKey(e => new { e.HeaderId, e.Version, e.StartDate });
entity.HasOne(e => e.Header).WithMany().HasForeignKey(f => f.HeaderId);
Upvotes: 2
Views: 873
Reputation: 205729
Fluent API do not support nested property expressions like e.Header.Id
.
As usual with shadow properties, you should refer to them by name using the string
overloads of the corresponding fluent API.
In your case:
entity.HasAlternateKey("HeaderId", "Version", "StartDate");
entity.HasOne(e => e.Header).WithMany().HasForeignKey("HeaderId");
Upvotes: 5