2

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.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
dkm3
  • 31
  • 5

2 Answers2

1

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"); 
dkm3
  • 31
  • 5
0

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; }
sebu
  • 2,824
  • 1
  • 30
  • 45