EF6在保存之前检查每个实体的更改

时间:2017-02-13 18:06:02

标签: asp.net-mvc entity-framework entity-framework-6

这是一种更新方法。从视图来看,用户可以更改现有学生,教师或主题的数据。

我将视图模型返回给由这3个不同实体组成的控制器:

- Viewmodel -

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)”错误。

如何在执行保存之前检查每个实体的更改,因此如果没有更改,我可以跳过实体?

1 个答案:

答案 0 :(得分:1)

如果您想检查实体的更改,您需要查询它们,以便以下解决方案可能满足您:

如果查询实体然后修改它们,则更改跟踪器将自动为您执行此操作,您无需为此编写代码。所以你可以使用以下代码:

mins_to_hours(In, H, M):-
    In<60,
    H = 0,
    M is In.
mins_to_hours(In, H, M):-
    In>=60,
    In1 is In-60,
    H1 is H+1,
    mins_to_hours(In1, H1, M).

只有在修改了任何属性后才会更新实体。