dotnet / dotnet/efcore

Unnecessary `IS NOT NULL` filter on unique indexes for TPT tables on SQL Server

Open
#32,689 5 comments 2 reactions 0 assignees View on GitHub
area-model-building customer-reported
Dominant language
C#
Stars
14.8k
Forks
3.4k
PR merge metrics
PR metrics pending

Description

It appears there is an unnecessary `[ColumnName] IS NOT NULL` filter added to unique indexes on TPT tables when using SQL Server.

Minimum reproducible example:

```C#
public class BaseType
{
public int Id { get; set; }
}

public class DerivedType : BaseType
{
public string Name { get; set; }
}

public class MyContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder options) => options.UseSqlServer();

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity().ToTable(nameof(BaseType));

modelBuilder.Entity(entity =>
{
entity.ToTable(nameof(DerivedType));

entity.HasIndex(e => e.Name).IsUnique();
});
}
}
```

The resulting migration contains:

```C#
migrationBuilder.CreateTable(
name: "DerivedType",
columns: table => new
{
Id = table.Column(type: "int", nullable: false),
Name = table.Column(type: "nvarchar(450)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_DerivedType", x => x.Id);
table.ForeignKey(
name: "FK_DerivedType_BaseType_Id",
column: x => x.Id,
principalTable: "BaseType",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});

migrationBuilder.CreateIndex(
name: "IX_DerivedType_Name",
table: "DerivedType",
column: "Name",
unique: true,
filter: "[Name] IS NOT NULL");
```

Since the `Name` column is already not null, I would expect the index in the migration to look like:

```C#
migrationBuilder.CreateIndex(
name: "IX_DerivedType_Name",
table: "DerivedType",
column: "Name",
unique: true);
```

### Include provider and version information

EF Core version: 8.0.0
Database provider: Microsoft.EntityFrameworkCore.SqlServer
Target framework: .NET 8.0
Operating system: macOS 13.6.3
IDE: N/A

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.