EF Core - Unique constraint including navigation p

2019-07-30 19:20发布

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);

1条回答
Rolldiameter
2楼-- · 2019-07-30 19:39

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");
查看更多
登录 后发表回答