EF Core - Unique constraint including navigation property not detected in migration

六眼飞鱼酱① 提交于 2019-12-24 12:05: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:


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


来源:https://stackoverflow.com/questions/56518114/ef-core-unique-constraint-including-navigation-property-not-detected-in-migrat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!