是否存在 EF Core 不允许您在同一列上创建多个索引的原因?
builder
.ForSqlServerHasIndex(x => x.ColumnX)
.ForSqlServerInclude(nameof(TableA.ColumnA), nameof(TableA.ColumnB))
.HasFilter($"{nameof(TableA.ColumnX)} = 1 AND {nameof(TableA.IsDeleted)} = 0")
.HasName($"IX_{nameof(TableA)}_{nameof(TableA.ColumnX)}_Filter_1}");
builder
.ForSqlServerHasIndex(x => x.ColumnX)
.ForSqlServerInclude(nameof(TableA.ColumnA), nameof(TableA.ColumnB))
.HasFilter($"{nameof(TableA.ColumnX)} = 0 AND {nameof(TableA.IsDeleted)} = 0")
.HasName($"IX_{nameof(TableA)}_{nameof(TableA.ColumnX)}_Filter_0}");
以上只是我尝试做的示例。 EF Core 不会生成两个索引。相反,它只是为第一次出现生成一个索引,然后我必须手动编辑迁移脚本以获得第二个索引。
这不是 SQL 提示它吗?
最佳答案
我的要求与您的要求非常相似 - 同一属性的两个索引,但具有不同的过滤器。我刚刚发现 Entity Framework Core 使用索引属性作为索引标识符的困难方法。 the documentation 证实了这一点关于创建索引:
EF Core only supports one index per distinct set of properties. If you use the Fluent API to configure an index on a set of properties that already has an index defined, either by convention or previous configuration, then you will be changing the definition of that index. This is useful if you want to further configure an index that was created by convention.
有可能绕过此行为,方法是手动将第一个索引添加回模型快照、迁移和迁移的快照。这是我们采取的路线,一切都按预期进行。但是,每次生成后续迁移时,它都会删除第一个索引,我们必须继续手动将其添加回去。如果我们可以使用名称作为索引的唯一标识符而不是使用索引属性列表,那就太好了。
顺便说一句,在您发布的示例中,您可以使用 IN()
运算符并创建以下单个索引来涵盖这两种情况:
builder
.ForSqlServerHasIndex(x => x.ColumnX)
.ForSqlServerInclude(nameof(TableA.ColumnA), nameof(TableA.ColumnB))
.HasFilter($"{nameof(TableA.ColumnX)} IN (1, 2) AND {nameof(TableA.IsDeleted)} = 0");
更新 - 2021 年 11 月 17 日
此问题已在 EntityFramework 5.0 中得到解决。 From the documentation :
Multiple indexes are now allowed on the same set or properties. These indexes are now distinguished by a name in the model. By convention, the model name is used as the database name; however it can also be configured independently using HasDatabaseName.
关于c# - EF 核心 : creating multiple filtered indexes on the same column,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58091019/