我有一个由电影和演员组成的模型,目前正在更新已经存在的电影(里面填充了信息和演员的明星)我用这个
public void Update(Movie item)
{
db.Entry(item).State = EntityState.Modified;
}
但是我如何才能这样做呢?如果我添加一部已经存在于DB中的演员的电影,那么这些电影不会再被添加而只是被忽略了?
答案 0 :(得分:0)
所以你有一个Movie
类和一个具有多对多关系的Actor
类:
电影可以有很多演员,演员可以出现在很多电影中。
See this link to see how the many-to-many is configured
如果您正确配置多对多,则无需担心现有演员在新电影中出现时会再次添加。
以下代码将说明这一点:
public class Movie
{
public int Id {get; set;}
public string Title {get; set;}
public virtual ICollection<Actor> Actors {get; set;}
}
public class Actor
{
public int Id {get; set;}
public string Name {get; set;}
public virtual ICollection<Movie> Movies {get; set;}
}
public class MyDbContext : DbContext
{
public DbSet<Movie> Movies {get; set;}
public DbSet<Actor> Actors {get; set;}
}
public void Test()
{
// create some actors
var actor1 = new Actor() { Name = "Actor 1"}
var actor2 = new Actor() { Name = "Actor 2" };
var actor3 = new Actor() { Name = "Actor 3" };
// add a movie with some of these actors
var movieToAdd = new Movie()
{
Title = "Hello Dolly",
Actors = new List<Actor>() {actor1, actor2},
};
var addedMovie = dbContext.Movies.Add(movieToAdd);
dbContext.SaveChanges();
// add another movie, with one existing actor and one not-existing actor
var otherMovieToAdd = new Movie()
{
Title = "Dracula",
Actors = new List<Actor>(){actor3, actor2},
};
var otherAddedMovie = dbContext.Movies.Add(otherMovieToAdd);
dbContext.SaveChanges();
// check the existing actors
foreach (var actorName in dbContext.Actors.Select(actor => actor.Name))
{
Console.WriteLine(actorName);
}
}
输出
Actor 1
Actor 2
Actor 3
请注意,虽然您没有专门添加任何Actor,但是添加了它们,因为它们出现的电影已添加。任何现有的演员(Id不等于零的演员)都不会再次添加。
所以问题的答案是:如果正确配置多对多关系,则不必担心现有的actor会被添加两次。