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
.