1

我有以下型号

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 表。帮助?如果您发现任何不相关的错误或我应该知道的事情,请不要犹豫指出它们。

4

1 回答 1

0

这似乎是一系列问题的结果,从需要使用 fluent api 告诉它不要在删除时级联到将 User 类的虚拟属性设置为 ICollection<>。我也在使用类似的东西

 public virtual ProjectDoc ProjectDoc { get; set; }

代替

 public ProjectDoc ProjectDoc { get; set; }

不知道到底有什么区别,但它现在正在工作。

于 2012-12-14T04:18:06.810 回答