Jackal
Jackal

Reputation: 3521

Create unique constraint on column

I have this model

public class Record
{
    public int Id {get;set;}
    public int Client {get;set;}
    public bool IsActive {get;set;}
}

I want to create a constraint for the IsActive column.

Only 1 record can be active per client.

How can i achieve this on the model?

Upvotes: 2

Views: 240

Answers (1)

Soheil Alizadeh
Soheil Alizadeh

Reputation: 3066

You need to create a filtered index for your column the ef core have filter index feature and you can configure it in your dbcontext with overriding OnModelCreating method.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
   modelBuilder.Entity<Record>(entity =>
   {
       entity.HasIndex(e => e.Client)
        .HasName("Record_Filtered_Index")
        .HasFilter("([IsActive]=(1))");
   });
}

Upvotes: 2

Related Questions