관련 엔터티를 업데이트하는 동안 오류 메시지가 표시됩니다.Entity Framework 업데이트 관련 엔터티
새로 만들면 괜찮습니다.
오류 메시지가 말 :
참조 무결성 제약 조건 위반이 발생 다음 참조 제한 조건은 관계 원금과 종속 개체 사이에 일치하지 않는 정의하는 속성 값.
제 코드를 검토해보고 잘못된 길을 알려주십시오.
우선 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;
}
}
대단히 감사합니다. 이제는 EF가 어떻게 작동하는지 이해합니다. 존재하는 데이터로 대체 될 것이라고 생각했기 때문에 존재 한 데이터를로드했습니다. ^^ 질문 하나 더 물어봐도 될까요?, EF가 AttachedFile과 관련된 Note.id를 아는 방법 .noteId? 나는 어느 곳에서나 정의하지 않았고, 사용할 수없는 MYISAM도 FK를 정의합니다. –
예를 들어, AttachedFile 테이블에 noteNo 필드를 추가하고 noteNo 변수를 엔티티 클래스에도 추가합니다. 그리고 나는 응용 프로그램을 실행, 잘 작동, EF 전혀 혼란스러워하지 않았다 :). 이제 내가 FK를 바꾸기를 원한다면 noteID가 아닌가요? 어떻게해야합니까? –
@Expertwannabe : 첫 번째 주석 정보 : EF는 매핑을 추론하기 위해 특정 명명 규칙을 적용하기 때문에이를 알고 있습니다. 이 경우 : 그것은'AttachedFile' 클래스를 참조하는'AttachedFiles' 콜렉션을 봅니다. 그런 다음이 클래스에서 "클래스 이름 + PK + 속성 이름"(='NoteId', 대소 문자는 중요하지 않음)이라는 속성이 있는지 확인합니다. 그리고 네, 거기에 하나가 있습니다 :'noteId'. 그런 다음 외부 키 속성이어야한다고 가정합니다.'MySpecialId'와 같은 다른 이름을 주면 FK 속성을 찾을 수 없으며 예외가 발생하지 않습니다. – Slauma