更新时间:2023-12-04 12:30:22
当连接的实体重新连接时,默认情况下它们处于添加状态。
public int CreateExercise(练习newExercise){
db.Exercises.Add(newExercise);
//将所有附加的用户设置为不变。
db.ChangeTracker.Entries< User>()。ToList()。ForEach(p => p.State = EntityState.Unchanged);
db.SaveChanges();
return newExercise.ExerciseId;
}
I have the following:
public int CreateExercise(Exercise newExercise) {
db.Exercises.Add(newExercise);
db.SaveChanges();
return newExercise.ExerciseId;
}
Where Exercise is the following:
public class Exercise {
public Exercise() {
Users = new Collection<User>();
}
[Key]
[Required]
public int ExerciseId { get; set; }
[StringLength(300, ErrorMessage = "The value cannot exceed 300 characters. ")]
public string Title { get; set; }
public virtual ICollection<User> Users{ get; set; }
}
When I create a new Exercise, sometimes pre-existing Users come with it, Id included. Even with an existing UserId
specified for these Users
, new User
entries are getting added here. I only want to add associations, not new users - I'd imagine EF is smart enough to figure this out? What am I doing wrong?
I'm just trying to avoid having to loop through all Users attached to a new Exercise, clearing them out before Add
ing, making sure they exist, adding the exercise, and then adding each individual user, finally calling SaveChanges
.
When disconnected entities are reattached they are in Added state by default.
You can change the state after attaching the exercise.
public int CreateExercise(Exercise newExercise) {
db.Exercises.Add(newExercise);
// set all attached users to unchanged.
db.ChangeTracker.Entries<User>().ToList().ForEach(p => p.State = EntityState.Unchanged);
db.SaveChanges();
return newExercise.ExerciseId;
}