2012-10-31 245 views
0

嘗試更新相關實體時收到錯誤消息。實體框架更新相關實體

當創建新的是好的。

該錯誤消息說:出現

參照完整性約束違規:定義 參照約束不本金和相關對象的關係之間是一致的特性值。

請檢查我的代碼,並告訴我我做錯了什麼。

首先,DB是Mysql MyISAM。

實體類

[Table("note")] 
public class Note 
{ 
    [Key] 
    public int id { get; set; } 

    [Required(ErrorMessage="Content is required")] 
    [DisplayName("Note")] 
    public string content { get; set; } 
    public DateTime date { get; set; } 

    [Required(ErrorMessage = "User ID is required")] 
    [DisplayName("User ID")] 
    public string userId {get; set;} 
    public Boolean isPrivate { get; set; } 

    [DisplayName("Attach File")] 
    public virtual ICollection<AttachedFile> AttachedFiles { get; set; } 

} 

[Table("attachedfile")] 
public class AttachedFile 
{ 
    [Key] 
    public int id { get; set; } 
    public int noteId { get; set; } 
    public string fileName { get; set; } 
} 

控制器,

​​

enter image description here

回答

1

通過的note狀態設置爲Modified EF會附上相關的實體,特別是新創建的AttachedFile,到上下文中,但在狀態Unchanged。儘管如此,您還沒有設置正確的外鍵屬性值(如果實體不在狀態Added中,則必須這樣做)。這樣做將消除異常:

list.Add(new AttachedFile 
{ 
    noteId = note.id, 
    fileName = fileName 
}); 

但新AttachedFile將不會被添加到您的數據庫,因爲它不是在Added狀態。

我希望這是作品,如果你更新/插入後調用updateAttachFile ...

if (note.id > 0) 
    unitOfWork.NoteRepository.UpdateNote(note); 
else 
    unitOfWork.NoteRepository.InsertNote(note); 
updateAttachFile(note, attFile); 
unitOfWork.Save(); 

...因爲變化檢測SaveChanges發生承認新的實體,並把它放入Added狀態自動。

附註:我不知道爲什麼要使用unitOfWork.AttachedFileRepository.Get...加載現有的AttachedFiles。在我看來,對於兩種情況Update和Insert都應該使用空的list

+0

非常感謝,現在我明白了EF如何工作。我加載了已有的數據,因爲我認爲它會替換已有的數據。^^我可以再問一個問題嗎?,EF如何知道Note.id與AttachedFile.noteId有關?我沒有在任何地方定義,也是MYISAM,沒有定義FK。 –

+0

例如,我將noteNo字段添加到AttachedFile表中,並將noteNo變量添加到實體類中。而我運行的應用程序,它工作正常,EF沒有任何困惑:)。現在如果我想要我更改FK注意不noteID,我應該怎麼做? –

+0

@Expertwannabe:關於你的第一個評論:EF知道它,因爲它應用某些命名約定來推斷映射。在這種情況下:它看到引用「AttachedFile」類的'AttachedFiles'集合。然後看看在這個類中是否有一個名爲「註釋類名+ PK屬性名」的屬性(= NoteId,大小寫無關緊要)。是的,有一個:'noteId'。然後它假定這必須是外鍵屬性。如果你想給它另一個名字,比如'MySpecialId',它不會找到FK屬性,並且你的異常不會發生。 – Slauma