EF Core 2.1更新相关数据

时间:2018-08-03 02:33:50

标签: entity-framework asp.net-core-2.0 asp.net-core-webapi ef-core-2.1

我的编辑控制器

 public async Task<IActionResult> Put(long id, [FromBody] Student student)
 {
        var p = await _Context.Students
            .Include(t => t.PhoneNumbers)
            .Include(t => t.StudentCourses)
            .SingleOrDefaultAsync(t => t.Id == id);

        if (p == null)
        {
            return NotFound();
        }

        p.PhoneNumbers = student.PhoneNumbers;
        p.StudentCourses = student.StudentCourses;
        _Context.Update(p);
        await _Context.SaveChangesAsync();

        return NoContent();
    }

当我尝试更新相关实体时,我收到以下错误

System.InvalidOperationException: The instance of entity type 'PhoneNumber' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.

我是否以错误的方式进行更新。请帮助我纠正它。我也不确定Direct _context.update()和_context.students.update()之间的区别。请赐教。

0 个答案:

没有答案