Pascal Pascal - 25 days ago 7
C# Question

EntityState.Modified does work differently on updating in EF Core vs EF 6

When I run this method with EF 6 the student was updated!

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


When I run this method with EF 7 nothing has changed in the database!

What do I wrong? I do not want to retrieve the entity first to update it!

UPDATE

I put a try/catch around the SaveChanges and got this error message:

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.


Is it a problem when I set the WHOLE entity state to modified, when one of its properties (e.g. Student.SchoolclassId) is a foreign key?

UPDATE 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; }
}


When the Update method is entered the student FirstName/LastName properties have the new values!

Answer

Your error is stating that your Student has SchoolclassId and that value does not exist in the foreign table which is Id in Schoolclasses table.

Check the value of SchoolclassId before calling SaveChanges. Most likely this value does not exist in Schoolclasses table.

In other words this error is not because of EF 6 vs EF 7 but due to a foreign key not being found in the related table.