I have a scenario in which I want to update the movie object and its many relationships with genres.
The Genres navigation property in the movie contains Genre stub objects that contain only GenreID , because I want to save the database query for all genres.
See the code below for a fair explanation. The problem is that I need to attach my "Stub" genres to the context so that EF changes only the M: M relationship and does not try to create new records in the genre. This causes an error if the genre is already tied to the context since loading the genres of the current movie. It cannot track multiple objects with the same keys.
How should this be handled? Is there a way to check if the context is already tracking an object, or is there a better solution to this problem?
Code below:
public override void Update(Movie movie) { //Backup new genres before clearing genres from movie var newGenres = movie.Genres; movie.Genres = new List<Genre>(); _ctx.Entry(movie).State = System.Data.EntityState.Modified; //Load movie current genres from DB and remove them _ctx.Entry(movie).Collection(m => m.Genres).Load(); movie.Genres.Clear(); //Add new genres to movie foreach (var genre in newGenres) { _ctx.Genres.Attach(genre); //Problem if genre already attached movie.Genres.Add(genre); } }
Thanks for any help.
source share