现有表上的EF One to Zero或One关系导致数据库更新错误

时间:2017-04-10 14:21:11

标签: c# entity-framework ef-code-first

实体框架6 - 代码优先。 我们已经在我们的数据库上有他们的表的现有类了一段时间。这些表已包含我们无法删除的数据。

我们尝试在它们之间添加“one to zero-or-one”关系,如下所示:

public class Session
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [ForeignKey("User")]
    public long Id { get; set; }
    ...
    public virtual User User { get; set;}
}

public class User
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [ForeignKey("Session")]
    public long Id { get; set; }
    ...
    public virtual Session Session { get; set;}
}

这是根据上述变化创建的迁移:

public partial class AddingSessionAndDialogOneToOneRelation : DbMigration
{
    public override void Up()
    {
        CreateIndex("dbo.Users", "Id");
        AddForeignKey("dbo.Users", "Id", "dbo.Sessions", "Id");
    }

    public override void Down()
    {
        DropForeignKey("dbo.Users", "Id", "dbo.Sessions");
        DropIndex("dbo.Users", new[] { "Id" });
    }
}

但是当我们运行Update-Database命令时,我们收到此错误:

  

ALTER TABLE语句与FOREIGN KEY约束“FK_dbo.Users_dbo.Sessions_Id”冲突。冲突发生在数据库“SVC_AAA”,表“dbo.Sessions”,列'Id'。

1 个答案:

答案 0 :(得分:1)

我认为你过度复杂的类定义和两个ID上的[DatabaseGenerated(DatabaseGeneratedOption.Identity)]属性也可能导致问题。它应该只能在用户ID上,但如果您遵循Code-First密钥约定,则根本不需要它。

以下代码在没有其他DataAnnotations的情况下运行良好:

public class Student
{
    public Student() { }

    public int StudentId { get; set; }
    public string StudentName { get; set; }

    public virtual StudentAddress Address { get; set; }

}

public class StudentAddress 
{
    [ForeignKey("Student")]
    public int StudentAddressId { get; set; }

    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string City { get; set; }
    public int Zipcode { get; set; }
    public string State { get; set; }
    public string Country { get; set; }

    public virtual Student Student { get; set; }
}

您可以在以下位置找到许多用于创建代码优先关系的示例:http://www.entityframeworktutorial.net/code-first/configure-one-to-one-relationship-in-code-first.aspx

<强>更新

对于更复杂的类,请尝试以下操作:

public class Session
{
    [Key]
    [ForeignKey("User")]
    public long Id { get; set; }
    ...
    public virtual User User { get; set;}
}

public class User
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long Id { get; set; }
    ...
    public virtual Session Session { get; set;}
}