Skip to content

SQL Server: a unique complex index over nullable columns admits only one row without a value #88

Closed

Description

@CaffeinatedCoder

Problem

SQL Server treats NULLs as equal in a unique index. EF Core's SqlServerIndexConvention therefore gives its own unique indexes over nullable columns a WHERE [c] IS NOT NULL filter. A unique complex index got none: an optional complex property, whose columns are all nullable, admits one row without a value and refuses the second.

public Registration? Registration { get; set; }                      // optional complex property
b.HasIndex(x => x.Tag).IsUnique();                                   // native, string? Tag
b.HasComplexIndex(x => x.Registration!.Vin, isUnique: true, indexName: "ux_complex_vin");

Rendered with the migration's target model, as database update does:

CREATE UNIQUE INDEX [ux_native_tag] ON [cars] ([Tag]) WHERE [Tag] IS NOT NULL;
CREATE UNIQUE INDEX [ux_complex_vin] ON [cars] ([Registration_Vin]);

The migration applies; then, on Azure SQL Edge, the second car without a registration fails: Cannot insert duplicate key row in object 'dbo.cars' with unique index 'ux_complex_vin'. The duplicate key value is (<NULL>). PostgreSQL and SQLite allow many NULLs in a unique index, so this is SQL Server only.

Note for tests: rendering with model: null (as MigrationHarness.SqlServerSql does) hides this, because EF's generator then applies its pre-2.0 "legacy" filter (UseLegacyIndexFilters).

Fix

The SQL Server differ gives a unique, nonclustered complex index declared without a filter [c] IS NOT NULL AND … over its nullable key columns, as EF's convention does. Gated on the model's rendering version (bumped to 3), so a snapshot from an earlier 5.x resolves the old way and existing indexes are rebuilt once instead of never.

Changed answer

The first migrations add after upgrading drops and re-creates each such index with the filter. Ships in a minor with a ### Changed answers row.

Found by the 5.5.0 pre-tag analysis (core and SQL Server). Present since the SQL Server satellite shipped.

Activity

  1. added this to the 5.5.0 milestone on Oct 19, 2026
  2. added
    bug
    silent
    severity/high
    package/core
    package/sqlserver
    area/indexes
    on Oct 19, 2026
  3. added a commit that references this issue on Oct 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area/indexesbugpackage/corepackage/sqlserverseverity/highsilent

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions