簡體   English   中英

asp.net mvc 更新數據庫中的項目時如何更新數據庫(數據庫未正確更新)?

[英]asp.net mvc How do you update a database when you update an item in it (database not updating correctly)?

我有這個 function 更新學生(用戶)的某些信息

public static bool UpdateStudent(this DBEntities1 DB, StudentView studentView)
        {
            Student studentToUpdate = DB.Students.Find(studentView.idStudent);
            studentView.CopyToStudent(studentToUpdate);
            DB.Entry(studentToUpdate).State = EntityState.Modified;
            DB.SaveChanges();
            return true;
        }

當學生更改自己的信息時,沒有問題,數據庫更新沒有問題。 問題是當管理員更改信息(停用帳戶)時,它會更改數據庫中的值,但僅在管理員方面。 從學生方面來看,他不受更改的影響,但管理員認為他已停用,當我檢查數據庫時,學生被視為已停用。 就像學生登錄時,他在數據庫中取的是以前的舊值,而不是新值。 這是停用學生的 function:

public static bool DeactivateStudent(this DBEntities1 DB, StudentView studentView)
        {

            OnlineStudents.RemoveSessionStudent(studentView); //tried to see if it was taking the student from the online session

            studentView.active = false;
            BeginTransaction(DB);
            if (studentView.admitted) //delete rep if accepted
            {
                DB.Representatives.Remove(DB.FindRepbyStudentId(studentView.idStudent));
                studentView.admitted = false;
            }
            DB.UpdateStudent(studentView);
            AddDeletedStudent(DB, studentView); //add deleted student
            
            if (InscriptionExist(DB, studentView.idStudent)) //delete inscription
                DeleteStudentInscription(DB, studentView.idStudent);

            DB.WriteStudentLog(studentView.idStudent, LogActions.deleteAccount);
            DB.SaveChanges();
            Commit();
            return true;
        }

我不明白為什么一方面它需要新的數據庫值,而另一方面卻沒有。 當我關閉應用程序並重新啟動它時,學生就會獲得更新的新信息。

在第一種情況下,您使用 DB.Students.Find (studentView.idStudent) 查找要更新的學生,使用 StudentView.CopyToStudent 方法您可能只更新您需要的數據(從而防止過度發布),然后保存更改。

第二個程序對我來說似乎不太清楚。 在第二種情況下,嘗試使用相同的過程,除了只更新被承認的標志。

也許您也可以考慮處理並發沖突。

暫無
暫無

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

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