添加迁移后尝试“更新数据库”时出现此错误

时间:2020-09-07 14:03:10

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

尝试从程序包管理器控制台更新数据库后出现此错误。这是一些代码。类用户已经在数据库中,我正尝试将Poslovnica类迁移到服务器。

在参考表“用户”中没有与外键“ FK_Poslovnica_User_UserID”中的参考列列表匹配的主键或候选键。 无法创建约束或索引。查看先前的错误。

 public class Poslovnica
{
    public int PoslovnicaID { get; set; }
    [Required]
    public string Naziv { get; set; }

    public string Adresa { get; set; }

    public User User { get; set; }

    public int? UserID { get; set; }
}

我已经添加了一些带有外键UserID且没有任何问题的类

 public class User
{
    public int userID { get; set; }

    

    [Required(AllowEmptyStrings = false)]
    [MaxLength(64)]
    public string ime { get; set; }
   
    
}

迁移中的模型构建器

 modelBuilder.Entity("ClassLibrary1.Models.Poslovnica", b =>
            {
                b.Property<int>("PoslovnicaID")
                    .ValueGeneratedOnAdd()
                    .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);

                b.Property<string>("Adresa");

                b.Property<string>("Naziv")
                    .IsRequired();

                b.Property<int?>("UserID");

                b.HasKey("PoslovnicaID");

                b.HasIndex("UserID");

                b.ToTable("Poslovnica");
            });

迁移构建器

 migrationBuilder.CreateTable(
            name: "Poslovnica",
            columns: table => new
            {
                PoslovnicaID = table.Column<int>(nullable: false)
                    .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
                Naziv = table.Column<string>(nullable: false),
                Adresa = table.Column<string>(nullable: true),
                UserID = table.Column<int>(nullable: true)
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_Poslovnica", x => x.PoslovnicaID);
                table.ForeignKey(
                    name: "FK_Poslovnica_User_UserID",
                    column: x => x.UserID,
                    principalTable: "User",
                    principalColumn: "userID",
                    onDelete: ReferentialAction.Restrict);
            });

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

您在PoslovnicaUser之间存在1对1的关系,但是Poslovnica中的外键与User中的主键不匹配。

userID中的属性User重命名为UserID,以匹配外键,因为按照惯例,因此它们必须匹配,以便ef core可以使用关系。并重新更新

修改

可能UserID在表Users中未被识别为主键 将以下属性添加到UserID中:

 public class User
{
    [Key] 
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)] 
    public int UserID { get; set; }   
}

并更新您的数据库。