2012-12-13 106 views
0

我有以下型號實體框架的遷移:INSERT語句衝突與外鍵約束

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 = "[email protected]", FacebookID = "123123124123", Admin = true, Authorized = true }, 
    new User { UserID = 2, FirstName = "Dale", LastName = "Dole", Email = "[email protected]", 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表格有效。幫幫我?如果你發現任何不相關的錯誤或我應該知道的事情,請不要猶豫,指出它們。

+0

難道是'User'有一個標識coulumn UserId',所以腳本中的值被忽略? (並且Id = 1的用戶已被刪除) –

+0

您是否也在'Project'中插入'UserID = 1'? –

+0

Gert,是的,有一個UserID = 1的項目行。 –

回答

0

這似乎是由於需要使用流利的api來告訴它不級聯刪除以將用戶類上的虛擬屬性設置爲ICollection <>所導致的一系列問題。我也使用像

public virtual ProjectDoc ProjectDoc { get; set; } 

而不是

public ProjectDoc ProjectDoc { get; set; } 

不知道的區別到底是什麼,但它的工作現在。

+0

您至少失去了延遲加載功能if不是通過去除「虛擬」來完成整個關係 –

相關問題