在EF Core与EF 6中进行更新时,EntityState.Modified的工作方式不同

时间:2016-11-01 19:43:34

标签: c# entity-framework-6 entity-framework-core

当我使用EF 6运行此方法时,学生已更新!

 public async Task Update(Student student)
        {
            context.Entry(student).State = EntityState.Modified;
            await context.SaveChangesAsync();
        }

当我使用EF 7运行此方法时,数据库中没有任何变化!

我错了什么?我不想先检索实体来更新它!

更新

我在SaveChanges周围放了一个try / catch,收到了这条错误消息:

The UPDATE statement conflicted with the FOREIGN KEY constraint "FK_Students_Schoolclasses_SchoolclassId". The conflict occurred in database "TGBData", table "dbo.Schoolclasses", column 'Id'.
The statement has been terminated.

当我将其中一个属性(例如Student.SchoolclassId)设置为外键时,将WHOLE实体状态设置为已修改时,是否存在问题?

更新2

public class Student
{
    public Student()
    {
        StudentsTests = new HashSet<StudentTest>();
        StudentsSubjects = new HashSet<SubjectStudent>();
    }

    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public ISet<StudentTest> StudentsTests { get; set; }
    public ISet<SubjectStudent> StudentsSubjects { get; set; }
    public Schoolclass Schoolclass { get; set; }
    public int SchoolclassId { get; set; }
}

public class Schoolclass
{
    public Schoolclass()
    {
        Students = new HashSet<Student>();
        Tests = new HashSet<Test>();
    }

    public int Id { get; set; }
    public string Number { get; set; }
    public ISet<Student> Students { get; set; }
    public ISet<Test> Tests { get; set; }

    public Schoolyear Schoolyear { get; set; }
    public int SchoolyearId { get; set; }
}

当输入Update方法时,学生FirstName / LastName属性具有新值!

1 个答案:

答案 0 :(得分:0)

您的错误表明您的学生有SchoolclassId,并且该值在校园表中为Id的外表中不存在。

在调用SaveChanges之前检查SchoolclassId的值。很可能这个值在Schoolclasses表中不存在。

换句话说,此错误不是因为EF 6与EF 7,而是由于在相关表中找不到外键。