我有两个表,分别是城市和县。它们彼此相关。尽管它们之间只有一种关系,但 EF 在数据库中创建了两个重复的键。我使用的是 EF 6.0.0.0。示例代码如下:
public class County : BaseEntity
{
public County()
{
RegardingCity = new City();
}
public string Name { get; set; }
public int CityID { get; set; }
public virtual City RegardingCity { get; set; }
}
public class City : BaseEntity
{
public City()
{
Counties = new List<County>();
}
public int Plate { get; set; }
public string Name { get; set; }
public virtual ICollection<County> Counties { get; set; }
}
and these are the mappers of them
class CountyMapper : EntityTypeConfiguration<BiLims.Data.Entities.Common.County>
{
public CountyMapper()
{
this.HasKey(c => c.Id);
this.Property(c => c.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
this.Property(c => c.Id).IsRequired();
this.Property(c => c.Name).IsRequired();
this.HasRequired(c => c.RegardingCity).WithMany().HasForeignKey(x => x.CityID);
}
}
class CityMapper : EntityTypeConfiguration<BiLims.Data.Entities.Common.City>
{
public CityMapper()
{
this.HasKey(c => c.Id);
this.Property(c => c.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
this.Property(c => c.Id).IsRequired();
this.Property(c => c.Name).IsRequired();
this.Property(c => c.Plate).IsRequired();
}
}
我做错了什么?我已经搜索过这个问题但找不到答案。
最佳答案
这是由您的流畅 API 映射引起的(顺便说一句,其中大部分都是多余的, Entity Framework 的约定将自行获取 ID 和 CityID 属性)。
通过声明 City.HasMany()
您引入了第二个一对多关系,因为这意味着一对多关系存在,但 City
没有它的导航属性。不过,City
确实具有指向同名Counties
的显式导航属性。
您可以安全地完全删除一对多映射!
关于c# - EF 为关系创建了两个重复的 FK,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25340052/