簡體   English   中英

實體框架在應該執行更新時執行插入

[英]Entity framework performing an Insert, when it should be doing an Update

EF v1出現了真正的問題。 我有一個很大的EDMX,可能映射了50個實體,但是這個實體使我感到悲傷。

該實體具有到其他實體的映射,這些實體實際上是引用表,但由於某種原因,它試圖插入而不只是更新自身。

這是我的代碼的一部分:

using (var context = new someEntities()) {
    var studentCourseJoin =
        context.StudentCourseJoinSet.Where(o => o.Code == scjCode).First();

    studentCourseJoin.EntryStatus = new EntryStatus { Code = viewModel.StudentDetails.EntryStatusCode };
    studentCourseJoin.ParentalInHigherEducation = new ParentalInHigherEducation { Code = viewModel.StudentDetails.ParentalInHigherEducationCode };
    studentCourseJoin.School = new School { Code = viewModel.StudentDetails.SchoolCode };

    studentCourseJoin.Institution = new Institution { Code = viewModel.StudentDetails.InstitutionCode };

    studentCourseJoin.LastSchoolEndYear = viewModel.StudentDetails.LastSchoolEndYear;
    studentCourseJoin.LastInstitutionEndYear = viewModel.StudentDetails.LastInstitutionEndYear;

    // Blows up here trying to do an insert on the studentCourseJoin.Institution.
    // But if I removed this one, then it will blow up on another one.
    context.SaveChanges(true);
}

如果有人有任何想法,他們會有所幫助。

嘗試在調用SaveChanges之前添加這些行:

ObjectStateEntry entry = context.ObjectStateManager.GetObjectStateEntry(studentCourseJoin);
entry.ChangeState(EntityState.Modified);

更新:

Institution嘗試以下方法:

studentCourseJoin.Institution = context.Institutions.FirstOrDefault(i => i.Code == viewModel.StudentDetails.InstitutionCode);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM