在EF Core與EF 6中進行更新時,EntityState.Modified的工作方式不同

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運行這個方法時,數據庫中沒有任何變化!

我錯了什麼?我不想先檢索實體來更新它!

UPDATE

我在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屬性具有新值!

一般承認的答案

您的錯誤是表明您的學生有SchoolclassId,並且該值在Schoolclasses表中為Id的外表中不存在。

在調用SaveChanges之前檢查SchoolclassId的值。很可能這個值在Schoolclasses表中不存在。

換句話說,此錯誤不是因為EF 6與EF 7,而是由於在相關表中找不到外鍵。



Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow