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
Post a Comment