【发布时间】:2012-12-14 12:18:06
【问题描述】:
我有以下型号
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 表。帮助?如果您发现任何不相关的错误或我应该注意的事情,请随时指出。
【问题讨论】:
-
会不会是
User有一个身份库UserId,所以脚本中的值被忽略了? (并且Id = 1的用户已被删除) -
您是否也在
Projects 中插入UserID = 1? -
Gert,是的,有一个用户 ID = 1 的项目行。
-
好吧,这真的很奇怪。也许您应该尝试设置 User 对象,而不是键值。
-
不确定我是否完全理解。我试过这个,假设这就是你的意思:用“User = new User { UserID = 1}”替换“UserID = 1”,但这只是在用户表中创建一个新行,在评论行中创建一个“0”。
标签: entity-framework ef-code-first entity-framework-migrations