I get an error message while trying to update related entity.
When create new one is OK.
The error message say :
A referential integrity constraint violation occurred: The property values that define the referential constraints are not consistent between principal and dependent objects in the relationship.
Please review my codes, and advice me what I am doing wrong.
First of all, DB is Mysql MyISAM.
Entity Class
[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; }
}
Controller,
[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;
}
}
