Search code examples
c#entity-frameworkmany-to-manyentity-framework-coreunique-constraint

Many-to-many relation and unique constraint. How do I do that in EF Core?


I have two entities Country and Business.

public class Country
{
    public int Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Business> Businesses { get; set; }

    public Country()
    {
        Businesses = new List<Business>();
    }
}

public class Business
    {
        public int Id { get; set; }
        public string Name { get; set; }

        public ICollection<Country> Countries { get; set; }

        public Business()
        {
            Countries = new List<Country>();
        }
    }

Country can have many Businesses inside it and Businesses can be present in many Countries. Business should be unique inside a country.

How can I make Business unique for the country in the many-to-many relation?


Solution

  • You can accomplish this with a composite key.

    First you need a third entity to represent the association:

    public class CountryBusiness {
        public int CountryId {get; set;}
        public Country Country {get; set;}
    
        public int BusinessId {get; set;}
        public Business Business {get; set;}
    }
    

    Then, you need to give it a composite key in your DbContext class:

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        builder.Entity<CountryBusiness>().HasKey(cb => new {cb.CountryId, cb.BusinessId});
    }