EF Core将带有两个FK的迁移添加到同一实体

时间:2018-07-19 18:08:31

标签: entity-framework asp.net-core .net-core entity-framework-core

我首先使用EF Core 2.0.3作为代码。

这是我的项目实体:

[Table("Project")]
public class ProjectEntity
{

    [Key]
    [Column("ProjectId")]
    public int Id { get; set; }
    public int ClientId { get; set; }
    [ForeignKey("ClientId")]
    public virtual ClientEntity Client { get; set; }
    public string Name { get; set; }
    public string Code { get; set; }

    public int? ParentId { get; set; }
    [ForeignKey("ParentId")]
    public virtual ProjectEntity Parent { get; set; }

    public int MasterId { get; set; }
}

我有一个FK要与ParentId一起投影 然后,我更改了项目模型,并将MasterId设置为FK:

    public int MasterId { get; set; }
    [ForeignKey("MasterId")]
    public virtual ProjectEntity Master { get; set; }

然后我运行add-migration命令,结果如下:

        migrationBuilder.DropForeignKey(
            name: "FK_Project_Project_ParentId",
            table: "Project");

        migrationBuilder.DropIndex(
            name: "IX_Project_ParentId",
            table: "Project");

首先迁移要删除ParentId Fk,为什么?

第二个还没有为MasterId添加任何Fk吗?

对此行为有任何想法吗?

1 个答案:

答案 0 :(得分:0)

似乎已EF Core self referencing not working if there are 2 foreign keys to self (Code first) #10123跟踪了此问题。

ProjectEntity配置两个以上的FKs时,我可以重现此问题。

我认为MasterId是可以为空的。我建议您尝试如下修改模型:

[Table("Project")]
public class ProjectEntity
{
    [Key]
    [Column("ProjectId")]
    public int Id { get; set; }
    public int ClientId { get; set; }
    public string Name { get; set; }
    public string Code { get; set; }
    public int? ParentId { get; set; }
    [ForeignKey("ParentId")]
    public virtual ProjectEntity Parent { get; set; }
    public int? MasterId { get; set; }
    [ForeignKey("MasterId")]
    public virtual ProjectEntity Master { get; set; }
    public int? MasterId1 { get; set; }
    //[ForeignKey("MasterId1")]
    public virtual ProjectEntity Master1 { get; set; }

}

然后通过下面的ForeignKey配置Fluent API

    builder.Entity<ProjectEntity>(entity =>
    {
        entity.HasOne(e => e.Master1).WithOne()
              .HasForeignKey<ProjectEntity>(e => e.MasterId1)
              .HasConstraintName("ForeignKey_Project_Master1");
        entity.HasIndex(e => new { e.MasterId1 })
              .IsUnique(false);
    });