2012-10-31 248 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