我正在使用.Net Core 2.1.200版本。
我具有以下类结构(简化版)
public class Workout
{
public int WorkoutID { get; set; }
public int UserID { get; set; }
public DateTime Date { get; set; }
public string Notes { get; set; }
public List<WorkoutExercise> Exercises { get; set; }
}
public class WorkoutExercise
{
public int WorkoutExerciseID { get; set; }
public int ExerciseID { get; set; }
public int ExerciseNo { get; set; }
public Workout Workout { get; set; }
public List<WorkoutExerciseSet> Sets { get; set; }
}
public class WorkoutExerciseSet
{
public int WorkoutExerciseSetID { get; set; }
public int Reps { get; set; }
public decimal Weight { get; set; }
public WorkoutExercise WorkoutExercise { get; set; }
}
因此,锻炼有一个练习列表,每个练习都有一套列表。
现在,当我想更新锻炼时,我希望能够添加/删除/更新任何WorkoutExercise或WorkoutExerciseSet。
我有以下API端点:
public IActionResult UpdateWorkout([FromBody] Workout workout)
{
Workout originalWorkout = _context.Workouts.Include(x => x.Exercises)
.ThenInclude(set => set.Sets)
.Where(x => x.WorkoutID == workout.WorkoutID)
.AsNoTracking()
.FirstOrDefault();
_context.Update(workout);
_context.SaveChanges();
//If there are no exercises in the parameter object and there were exercises saved previously
//We want to remove all saved exercises and corresponding sets
if(workout.Exercises.Count == 0 && originalWorkout.Exercises.Count > 0)
{
List<WorkoutExercise> removedExercises = originalWorkout.Exercises.ToList();
foreach (WorkoutExercise exercise in removedExercises)
{
List<WorkoutExerciseSet> removedSets = exercise.Sets.ToList();
_context.WorkoutExerciseSets.RemoveRange(removedSets);
}
_context.WorkoutExercises.RemoveRange(removedExercises);
}
_context.SaveChanges();
}
这只是从数据库中获取同一锻炼的保存版本,然后检查是否有任何锻炼被删除。如果有,那么我想删除这些练习。
现在,当我运行此命令时,我收到以下错误消息
The instance of entity type 'Workout' cannot be tracked because another instance with the key value 'WorkoutID' is already being tracked.
When attaching existing entities, ensure that only one entity instance with a given key value is attached.
上面的代码在行上中断
_context.WorkoutExerciseSets.RemoveRange(removedSets);
如果我将“ _context.Update(workout)”行移至第二个“ _context.SaveChanges()”之下,则会抛出相同的错误
_context.Update(workout);
有人对我应该采取的解决此问题的步骤有任何建议吗?
谢谢