尝试更新相关实体时收到错误消息。
当创建一个新的就可以了。
错误消息说:
发生参照完整性约束冲突:定义参照约束的属性值在关系中的主体对象和从属对象之间不一致。
请检查我的代码,并告诉我我做错了什么。
首先,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;
}
}