0

関連エンティティを更新しようとすると、エラー メッセージが表示されます。

新規作成でOKです。

エラーメッセージは言う:

参照整合性制約違反が発生しました: 参照制約を定義するプロパティ値が、リレーションシップ内のプリンシパル オブジェクトと従属オブジェクトの間で一貫していません。

私のコードを見直して、私が間違っていることを教えてください。

まず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; }
}

コントローラ、

[HttpPost]
public ActionResult Index(Note note, HttpPostedFileBase attFile)
{
    try
    {
    if (ModelState.IsValid)
    {
        updateAttachFile(note, attFile);
        if (note.id > 0)
        {
        unitOfWork.NoteRepository.UpdateNote(note);
        }
        else
        {
        unitOfWork.NoteRepository.InsertNote(note);
        }

        unitOfWork.Save();
        return RedirectToAction("Index");
    }
    }catch(DataException){
    ModelState.AddModelError("", "Unable to save changes. Try again please");
    }

    var notes = unitOfWork.NoteRepository.GetNotes();
    return View(new NoteViewModel() { noteList = notes.ToList(), note = new Note() });
}

private void updateAttachFile(Note note,HttpPostedFileBase attFile)
{
    if (attFile == null) return;

    List<AttachedFile> list;
    if (note.id > 0)
    {
    list = unitOfWork.AttachedFileRepository.Get(filter: q => q.noteId.Equals(note.id)).ToList();
    }
    else
    {
    list = new List<AttachedFile>();
    }

    var fileName = Path.GetFileName(attFile.FileName);
    fileName = fileName.Replace(" ", "");
    fileName = Regex.Replace(fileName, @"\s|\$|\#\%", "");
    var path = Path.Combine(Server.MapPath("~/App_data/uploads"), fileName);
    attFile.SaveAs(path);

    list.Add(new AttachedFile
    {
    fileName = fileName
    });

    note.AttachedFiles = list;
}
}

ここに画像の説明を入力

4

1 に答える 1

1

の状態noteModifiedEF に設定すると、関連するエンティティ、特に新しく作成されAttachedFileた がコンテキストにもアタッチされますが、状態は になりますUnchanged。ただし、正しい外部キー プロパティ値を設定していません (エンティティが状態でない場合に必要ですAdded)。これを行うと、例外が削除されます。

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

ただし、状態AttachedFileにないため、新しいものはデータベースに追加されませんAdded

updateAttachFileUpdate/Insertの後に呼び出すとうまくいくと思います...

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

...で発生する変更検出によりSaveChanges、新しいエンティティが認識され、Added自動的に状態になるためです。

補足として、既存の AttachedFiles を .xml でロードする理由がわかりませんunitOfWork.AttachedFileRepository.Get...。私の意見では、list更新と挿入の両方の場合に空の状態で機能するはずです。

于 2012-10-31T23:37:01.973 に答える