在包括 FK 列的多个列上创建唯一索引

Creating unique index over multiple columns that includes FK column

我正在使用 EntityFramework Core(代码优先,流畅 API)和 SQL Server 2012。我有两个 table:帐户和帐户类型。 AccountType 本质上是一个查找 table,具有映射到枚举的预定义值。它看起来像这样:

编号 |输入

0 |个人

1 |储蓄

2 | ...

我的帐户 table 有几个字段和 AccountType table 的 FK。看起来像这样:

编号 |帐户类型 ID |名称 |斐乐

1 | 0 |约翰·多伊 | A1

2 | 1 |简·杜 | A1

.....

在我的 DBContext class 中,我试图使 AccountTypeId + Name + Fila 字段成为唯一索引,因为这 3 个字段的组合在我的模型中始终是唯一的。当我这样做时:

Entity<Account>.HasIndex(p => new { p.AccountType, p.Name, p.File }).IsUnique();

尝试添加迁移时出现以下错误:

无法将 属性 'AccountType' 添加到实体类型 'Account',因为实体类型上已存在同名导航 属性 'Account'.

我不确定这是数据库问题还是 EF 问题。如果我从索引中删除 p.AccountType,我不会收到任何错误。

您可以尝试下图

注意:必须使用 primitive data type创建一个index

Entity<Account>.HasIndex(p => new { p.AccountTypeId , p.Name, p.File }).IsUnique();