EF Core-唯一约束,包括在迁移中未检测到的导航属性 [英] EF Core - Unique constraint including navigation property not detected in migration

查看:201
本文介绍了EF Core-唯一约束,包括在迁移中未检测到的导航属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试应用唯一的复合约束,约束的一部分是外键。我似乎可以使它起作用的唯一方法是在我的域类中显式定义外键,这是我要避免的。

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?

问题和解决方法适用于 HasAlternateKey HasIndex 。该解决方案构建良好,但是在创建迁移之前忽略了约束,直到shadow属性变成了域类中的不动产为止。

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

在将阴影属性HeaderID转换为真实的对象之后,这确实起作用:

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


推荐答案

Fluent API不支持嵌套属性表达式,例如 e.Header.Id

Fluent API do not support nested property expressions like e.Header.Id.

与阴影属性一样,应使用 name引用它们使用相应的Fluent API的 string 重载。

As usual with shadow properties, you should refer to them by name using the string overloads of the corresponding fluent API.

在您的情况下:

entity.HasAlternateKey("HeaderId", "Version", "StartDate");
entity.HasOne(e => e.Header).WithMany().HasForeignKey("HeaderId");

这篇关于EF Core-唯一约束,包括在迁移中未检测到的导航属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆