我有两个实体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>();
}
}
国家内部可以有许多企业,许多国家都有企业。企业在国内应该是独一无二的。
如何在多对多关系中为国家/地区创造独特的业务?
答案 0 :(得分:2)
您可以使用复合键完成此操作。
首先,您需要第三个实体来表示关联:
public class CountryBusiness {
public int CountryId {get; set;}
public Country Country {get; set;}
public int BusinessId {get; set;}
public Business Business {get; set;}
}
然后,您需要在DbContext类中为它提供一个复合键:
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<CountryBusiness>().HasKey(cb => new {cb.CountryId, cb.BusinessId});
}