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


i have 2 entities country , 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 , businesses can present in many countries. business should unique inside country.

how can make business unique country in many-to-many relation?

you can accomplish composite key.

first need third entity represent 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, need give composite key in dbcontext class:

protected override void onmodelcreating(modelbuilder builder) {     base.onmodelcreating(builder);     builder.entity<countrybusiness>().haskey(cb => new {cb.countryid, cb.businessid}); } 

Comments

Popular posts from this blog

javascript - Clear button on addentry page doesn't work -

c# - Selenium Authentication Popup preventing driver close or quit -

tensorflow when input_data MNIST_data , zlib.error: Error -3 while decompressing: invalid block type -