関連エンティティを更新しようとすると、エラー メッセージが表示されます。
新規作成で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;
}
}