多对多关系的SaveChanges失败了

时间:2012-09-04 19:44:48

标签: c# entity-framework

这是我的基地:

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

如何避免此异常?

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分:0)

检索影片种类,而不是每次都创建它。或者这太明显了?