修改后,IsModified在条目集合中始终为false

时间:2018-06-05 16:13:43

标签: c# entity-framework asp.net-core entity-framework-core

我与Entity Framework建立了多对多关系,如下所示:

public class Student
{
    public int StudentId { get; set; }
    public string Name { get; set; }

    public List<StudentCourse> StudentCourses { get; set; }
}

public class Course
{
    public int CourseId { get; set; }
    public string Name { get; set; }

    public List<StudentCourse> StudentCourses { get; set; }
}

public class StudentCourse
{
    public int StudentId { get; set; }
    public Student Student { get; set; }

    public int CourseId { get; set; }
    public Course Course { get; set; }
}

我有一种方法可以修改学生注册的课程,同时删除和添加学生的学生课程。

我想做的一件事是检查StudentCourses集合是否为学生修改过。我试图通过在学生条目上使用IsModified属性来做到这一点。

public async Task<Student> EditStudentAsync(int id)
{
    var existingStudent = await _dbContext.Students
            .Include(s => s.StudentCourses)
            .FirstOrDefaultAsync(s => s.Id.Equals(id));

    existingStudent.StudentCourses.RemoveAll(sc => 
        ...
        // courses to delete
    );
    existingStudent.StudentCourses.AddRange(
        ...
        // courses to add
    );

    // check if StudentCourses have been added to or deleted from
    bool coursesChanged = _dbContext.Entry(existingStudent)
                              .Collection(s => s.StudentCourses).IsModified;
    coursesChanged = _dbContext.Entry(existingStudent)
                         .Navigation("StudentCourses").IsModified;
    // do something if they changed

    await _dbContext.SaveChangesAsync();
    return existingStudent;
}

但是,即使我已经添加到集合中或从集合中删除,它也总是回归虚假。我试过这两种不同的方式,在学生条目上使用收集和导航,但两者都不起作用。

我应该采取不同的方式吗?

0 个答案:

没有答案