-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)「錯誤。
如何在保存之前檢查每個實體的更改,以便在沒有更改的情況下跳過實體?
當實體沒有被更改時,但是當實體是新的並且必須被添加時,不會拋出異常。 –
我認爲你需要將它們添加到DbSet,而不是手動搞亂更改狀態,但是我對你的應用程序並不瞭解。 – Casey
凱西 - 什麼意思是「將它們添加到DbSet」? – BattlFrog