c# - EF 核心 : creating multiple filtered indexes on the same column

标签 c# sql-server ef-core-2.2

是否存在 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/

相关文章:

c# - SSL通信的双向认证

sql-server - ogr2ogr 不创建表

entity-framework - SQL 超时已过期。操作完成前超时时间已过或服务器未响应

LinQ 查询中 lambda 表达式中的 C# 多个变量

c# - 在没有 OverflowException 的情况下将 "1.79769313486232E+308"转换为 double?

c# - 使用 C# 从 MS Access DB 检索表关系

sql - 删除...输出计数(已删除。*)

sql server 表类型冲突操作数

c# - 如果我忽略用于某个过程的 dbset,我将无法使用 EF Core 获取该过程

c# - 具有相同名称的多个内存数据库