dkm3
dkm3

Reputation: 31

Entity Framework - how to set column as unique related to another column

I am using Entity Framework and I have the following model class:

public class Test 
{
    public string Name { get; set; }
    public int SiteId { get; set; }    
    public bool IsPrimary { get; set; } 
}

How can I set the column IsPrimary to be unique in accordance with the SiteId?

For example I can have multiple records with the IsPrimary set to false for the same SiteId, but only one set to true.

Upvotes: 2

Views: 262

Answers (2)

sebu
sebu

Reputation: 2954

You can try with the following codes:

[Index("Index_SiteId_IsPrimary", 1, IsUnique = true)]
public int SiteId  { get; set; }

[Index("Index_SiteId_IsPrimary", 2, IsUnique = true)]
public bool IsPrimary { get; set; }

Upvotes: 0

dkm3
dkm3

Reputation: 31

finally found the solution! i can have multiple rows for the same siteId when isPrimary is false but only one when the isPrimary is true.

modelBuilder.Entity<MyTable>()
            .HasIndex(b => new { b.IsPrimary, b.SiteId })
            .IsUnique()
            .HasFilter("IsPrimary = 1"); 

Upvotes: 1

Related Questions