实体框架迁移:INSERT语句与FOREIGN KEY约束冲突

时间:2012-12-13 23:51:59

标签: entity-framework ef-code-first ef-migrations

我有以下型号

public class User
{
    public int UserID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string FacebookID { get; set; }
    public string GoogleID { get; set; }
    public string TwitterID { get; set; }
    public bool Admin { get; set; }
    public bool Authorized { get; set; }

    public virtual Comment Comment { get; set; }
    public virtual CommentReply CommentReply { get; set; }
    public virtual Project Project { get; set; }
    public virtual ProjectVote ProjectVote { get; set; }
    public virtual CommentReplyVote CommentReplyVote { get; set; }
    public virtual CommentVote CommentVote { get; set; }
    public virtual ProjectCoverVote ProjectCoverVote { get; set; }
}
public class Comment
{
    [Key]
    public int CommentID { get; set; }
    public int ProjectDocID { get; set; }
    public int UserID { get; set; }

    public string Text { get; set; }
    public string Annotation { get; set; }
    public string Quote { get; set; }
    public string Start { get; set; }
    public string End { get; set; }
    public string StartOffset { get; set; }
    public string EndOffset { get; set; }
    public DateTime DateCreated { get; set; }

    public virtual ICollection<CommentVote> CommentVote { get; set; }
    public virtual ICollection<CommentReply> CommentReply { get; set; }

    public virtual ProjectDoc ProjectDoc { get; set; }
    public virtual User User { get; set; } 
}

然后我在实体代码首次迁移中使用它作为种子方法的一部分:

 context.Users.AddOrUpdate(i => i.FirstName,
     new User { UserID = 1, FirstName = "Bob", LastName = "Dole", Email = "nobody@gmail.com", FacebookID = "123123124123", Admin = true, Authorized = true },
     new User { UserID = 2, FirstName = "Dale", LastName = "Dole", Email = "nobody@gmail.com", FacebookID = "123123124123", Admin = false, Authorized = true }
            );

context.Comments.AddOrUpdate(i => i.CommentID,
      new Comment { CommentID = 1, ProjectDocID = 1, UserID = 1, Text = "This is a comment", DateCreated = DateTime.Parse("Dec 03, 2011 12:00:00 PM") }
      );

这是我得到的错误。

System.Data.SqlClient.SqlException: 
The INSERT statement conflicted with the FOREIGN KEY constraint 
"FK_dbo.Comment_dbo.User_CommentID". The conflict occurred in database 
"TEST_ba6946e96d174b7bac9543ba614c8cf8", table "dbo.User", column 'UserID'.

如果我注释掉添加注释行的尝试,那么对于具有UserID字段的Projects表,它可以正常工作。救命?如果您发现任何不相关的错误或我应该注意的事情,请不要犹豫,指出它们。

1 个答案:

答案 0 :(得分:0)

这似乎是一系列问题的结果,需要使用流畅的api告诉它不要在删除时级联,将User类的虚拟属性设置为ICollection&lt;&gt;。我也在使用像

这样的东西
 public virtual ProjectDoc ProjectDoc { get; set; }

而不是

 public ProjectDoc ProjectDoc { get; set; }

不确定区别是什么,但它现在正在运作。

相关问题