Prevent EF from adding new child objects instead of just association when inserting new parent object?

asp.net-mvc c# entity-framework entity-framework-6

Question

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
0
6/24/2014 8:47:02 PM

Accepted Answer

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;
}
2
6/24/2014 9:01:10 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow