c# - EntityState.Modified 在 EF Core 和 EF 6 中更新时的工作方式不同

标签 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)是外键时,这会是一个问题吗?

更新 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 属性具有新值!

最佳答案

您的错误表明您的 Student 具有 SchoolclassId 并且该值不存在于外部表中,即 Schoolclasses 表中的 Id。

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

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

关于c# - EntityState.Modified 在 EF Core 和 EF 6 中更新时的工作方式不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40367503/

相关文章:

c# - Azure B2C Oauth : Could not establish trust relationship for the SSL/TLS secure channel

c# - 将 POCO 对象类和 DBContext 从 Entity Framework 6 模型中分离出来

c# - Entity Framework 7 审计日志

entity-framework - `DbContext.Database.BeginTransaction` 不能嵌套?

c# - 配置DbContext构造函数

c# - 在 EF Core 5 中保存相关数据(多对多)而不获取实际记录

c# - .Net 5.0 中对 WPF 的响应式扩展支持

c# - SandcaSTLe Help File Builder 找不到文档源

c# - 将子列表转换为父类型列表

c# - EF6.1.1 Code First 一对零/一关系