Here is my base :
And that it contains one movie (IDs comes from an external REST API) :
Movie movie = Movie.CreateMovie(999, "MyFirstMovie");
movie.Kinds.Add(Kind.Create(123,"Adventure"));
movie.Kinds.Add(Kind.Create(124,"Comic"));
movie.Actors.Add(Person.Create(321,"John Wayne"));
movie.Directors.Add(Person.Create(120,"John Woo"));
_context.AddToMovies(movie);
_context.SaveChanges();
Now, when I’m trying to insert a new movie, I got often an exception that said that I’m inserting an entity that already exists in the base.
Suppose I got another “Adventure” movie :
// Here all data comes from an external source and have no control over it.
using(Stream stream = myExternalStream)
{
Movie movie = Unserialize(stream);
_context.AddToMovies(movie);
}
// throws the exception because the kind "Adventure" already exists
_context.SaveChanges();
How can I avoid this exception?
I think you will have the check if the
Kindalready exists in the DB. If yes, replace the kind in themovie.Kindscollection by the kind loaded from the database. If no, keep the deserialized kind and create a newKindentity, for example like so: