2017-02-13 57 views
-1

這是一種更新方法。從視圖來看,用戶可以改變現有學生,老師或主題的數據。EF6在保存前檢查每個實體的更改

我返回一個視圖模型到由這些3個不同的實體的控制器:

- 視圖模型 -

public class StudentTeacherVM 
{ 
    public StudentModel Student { get; set; } 
    public TeacherModel Teacher { get; set; } 
    public SubjectModel Subject { get; set; } 
} 

在我在VM分割出的數據到控制器該數據庫的實體,然後將其保存:

 using (var db = new SchoolEntities()) 
     { 
      Student student = new Student() 
      { 
       StudentId = model.StudentId, 
       FirstName = model.FirstName, 
       LastName = model.LastName, 
       EmailAddress = model.StudentEmailAddress, 
       TeacherId = model.TeacherId 
      }; 

      Teacher teacher = new Teacher() 
      { 
       TeacherId = model.TeacherId, 
       FirstName = model.FirstName, 
       LastName = model.LastName, 
       EmailAddress = model.TeacherEmailAddress 
       SubjectId = model.SubjectId 
      }; 

      Subject subject = new Subject() 
      { 
       SubjectId = model.SubjectId, 
       Description = model.SubjectDescription, 
       Level = model.SubjectLevel 
      }; 

      db.Entry(subject).State = EntityState.Modified; 
      db.Entry(teacher).State = EntityState.Modified; 
      db.Entry(student).State = EntityState.Modified; 
      db.SaveChanges(); 
     } 

有時一個或多個科目不被修改,所以當代碼獲取到這一步,它拋出了「商店更新,插入或刪除小號聲明影響了意外的行數(0)「錯誤。

如何在保存之前檢查每個實體的更改,以便在沒有更改的情況下跳過實體?

+0

當實體沒有被更改時,但是當實體是新的並且必須被添加時,不會拋出異常。 –

+0

我認爲你需要將它們添加到DbSet,而不是手動搞亂更改狀態,但是我對你的應用程序並不瞭解。 – Casey

+0

凱西 - 什麼意思是「將它們添加到DbSet」? – BattlFrog

回答

1

如果要檢查更改的實體,您需要查詢他們,讓下面的解決方案也許滿足你:

如果查詢實體,然後對其進行修改,然後變更跟蹤器會自動爲做到這一點你和你不必爲此編寫代碼。因此,您可以使用以下代碼:

using (var db = new SchoolEntities()) 
    { 
     Student student = db.students.Single(x => x.StudentId == model.StudentId); 
     student.FirstName = model.FirstName; 
     student.LastName = model.LastName; 
     student.EmailAddress = model.StudentEmailAddress; 
     student.TeacherId = model.TeacherId; 

     Teacher teacher = db.teachers.Single(x => x.TeacherId == model.TeacherId); 
     teacher.FirstName = model.FirstName; 
     teacher.LastName = model.LastName; 
     teacher.EmailAddress = model.TeacherEmailAddress; 
     teacher.SubjectId = model.SubjectId; 

     Subject subject = db.subjects.Single(x => x.SubjectId == model.SubjectId); 
     subject.Description = model.SubjectDescription; 
     subject.Level = model.SubjectLevel; 

     db.SaveChanges(); 
    } 

只有在任何屬性已被修改的情況下,實體纔會更新。

相關問題