EF为一段关系创建了两个重复的FK

时间:2014-08-16 12:17:04

标签: c# mysql entity-framework

我有两张桌子,分别是城市和县。他们彼此相关。尽管它们之间只有一种关系,但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();

    }


}

These are the created tables and their relationship

我做错了什么?我搜索过这个,但我找不到答案。

1 个答案:

答案 0 :(得分:0)

这是由您的流畅API映射引起的(顺便说一下,其中大部分都是多余的,实体框架的约定将自行获取ID和CityID属性)。

通过声明City.HasMany()将第二个引入到多个关系,因为这意味着存在一对多关系,但City没有导航属性。 City 确实具有相同名称的Counties的显式导航属性。

您可以安全地删除一对多的映射!