Prevent EF from adding new child objects instead o

2019-06-10 00:51发布

问题:

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 Adding, making sure they exist, adding the exercise, and then adding each individual user, finally calling SaveChanges.

回答1:

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;
}