c# - EF 为关系创建了两个重复的 FK

标签 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

我做错了什么?我已经搜索过这个问题但找不到答案。

最佳答案

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

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

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

关于c# - EF 为关系创建了两个重复的 FK,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25340052/

相关文章:

mysql - COUNT和COUNT,GROUP BY先算

c# - 在模型和 AspNetUsers 之间加入(包含)

c# - Entity Framework : many to many relationship tables

c# - 在 C# 中更改或添加列表的索引类型

c# - .NET 中的错误?

c# - 警告 CA1065 Microsoft 设计未实现异常

mysql - 显示从属主机;有一个空的主机输出。如何获取从属主机?

mysql - 克隆MySQL数据库时,新网站是否需要更改 "current database"名称?

c# - 使用表达式树构建动态选择

c# - ComboBox KeyDown事件如何考虑最后按下的键