这是我的基地:
并且它包含一部电影(ID 来自外部 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();
现在,当我尝试插入新电影时,我经常遇到一个异常,说我正在插入一个已经存在于基础中的实体。
假设我有另一部“冒险”电影:
// 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();
我怎样才能避免这个异常?