0

这是我的基地:

并且它包含一部电影(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();

我怎样才能避免这个异常?

4

2 回答 2

1

我想你会检查Kind数据库中是否已经存在。如果是,则将集合中的种类替换为movie.Kinds从数据库加载的种类。如果不是,则保留反序列化的种类并创建一个新Kind实体,例如:

using(Stream stream = myExternalStream)
{
    Movie movie = Unserialize(stream);
    var newKindList = new List<Kind>();
    foreach(var kind in movie.Kinds)
    {
        var kindInDB = _context.Kinds
            .SingleOrDefault(k => k.KindId == kind.KindId);
        if (kindInDB != null)
            newKindList.Add(kindInDB);
        else
            newKindList.Add(kind);
    }
    movie.Kinds = newKindList;
    _context.AddToMovies(movie);
}
_context.SaveChanges();
于 2012-09-04T20:29:33.217 回答
0

检索电影类型,而不是每次都创建它。或者这很明显?

于 2012-09-04T19:54:29.263 回答