C# 多对多关系和唯一约束。我如何在EF Core中做到这一点?
我有两个实体:国家和企业C# 多对多关系和唯一约束。我如何在EF Core中做到这一点?,c#,entity-framework,many-to-many,entity-framework-core,unique-constraint,C#,Entity Framework,Many To Many,Entity Framework Core,Unique Constraint,我有两个实体:国家和企业 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 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>();
}
}
公共类国家
{
公共int Id{get;set;}
公共字符串名称{get;set;}
公共虚拟ICollection业务{get;set;}
公共国家()
{
业务=新列表();
}
}
公营业务
{
公共int Id{get;set;}
公共字符串名称{get;set;}
公共ICollection国家{get;set;}
公共事业()
{
国家=新名单();
}
}
一个国家可以有许多企业在其内部,企业可以出现在许多国家。企业在一个国家内部应该是独一无二的
在多对多关系中,我如何使业务在国家中独一无二?您可以使用复合密钥来实现这一点 首先,您需要第三个实体来代表关联:
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});
}
模型创建时受保护的覆盖无效(ModelBuilder)
{
基于模型创建(生成器);
builder.Entity().HasKey(cb=>new{cb.CountryId,cb.BusinessId});
}
您可以使用复合键完成此操作
首先,您需要第三个实体来代表关联:
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});
}
模型创建时受保护的覆盖无效(ModelBuilder)
{
基于模型创建(生成器);
builder.Entity().HasKey(cb=>new{cb.CountryId,cb.BusinessId});
}