问题
I have a scenario where I wish to update a movie entity and its many to many relationship with Genres.
The navigation property Genres
in movie contains stub Genre
objects that only contain the GenreID
because I want to save querying the DB for all genres.
See the code below, its fairly self explanatory. The problem is that I need to attach my "Stub" genres to the context so the EF will only modify the M:M relationship and not try to create new Genre records. This causes an error if a genre is already attached to the context from when I load the movie's current genres. It can't track multiple objects with the same keys.
How should this be handled? Is there a way to check if the context is already tracking the entity, or is there a better solution to this problem?
The code is 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's 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.
回答1:
You could try to avoid to attach the stubs if an entity with the same key is already attached:
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's current genres from DB and remove them
ctx.Entry(movie).Collection(m => m.Genres).Load();
var currentGenres = movie.Genres.ToList();
movie.Genres.Clear();
//Add new genres to movie
foreach (var genre in newGenres)
{
var currentGenre = currentGenres.SingleOrDefault(g => g.Id == genre.Id);
if (currentGenre != null)
movie.Genres.Add(currentGenre);
else
{
_ctx.Genres.Attach(genre);
movie.Genres.Add(genre);
}
}
}
来源:https://stackoverflow.com/questions/8522596/entity-framework-attach-trouble-in-many-to-many-update-scenario