Add discriminator filter for unique index on derived type

Open
#10,665 8 comments 1 reaction 1 assignee View on GitHub

@AndriySvyryd is already working on this.

Since Jan 12, 2018.

Assessment

This issue has not been assessed yet.

Description

area-relational-mapping
Issue description

Providing TPH & the following, simplified model:

    public class Organization
    {
        public string Name { get; set; }
    }
    public class Company : Organization { }
    public class Department : Organization { }

OnModelCreating: the following restriction is applied to all Organizations, so two Departments with the same name cannot be created.

    modelBuilder.Entity<Company>()
        .HasBaseType<Organization>();

    modelBuilder.Entity<Company>()
        .HasIndex(c => c.Name).IsUnique();
Workaround

We've found the following workaround, using a custom filter:

    modelBuilder.Entity<Organization>()
        .HasDiscriminator<int>("Discriminator")
        .HasValue<Company>(1)
        .HasValue<Department>(2);

    modelBuilder.Entity<Company>()
        .HasIndex(c => c.Name).IsUnique()
        .HasFilter("Discriminator IN (1)");

However, a more direct way of configuring it would be desirable.

Further technical details

EF Core version: 2.0.1
Database Provider: Microsoft.EntityFrameworkCore.SqlServer

Dominant language
C#
Stars
14.8k
Forks
3.4k
Avg merge
2d 5h
Merged PRs (30d)
134

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from dotnet/efcore

All issues in dotnet/efcore

Similar issues

More C# issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.