1

我有模型:

public class Movie
{
    [Key]
    public int MovieId { get; set; }

    public string Title{ get; set; }

    public ICollection<Actor> Actors { get; set; }
 }

public class Actor
{
    [Key]
    public int AtorId { get; set; }
    public string Nome { get; set; }

    public ICollection<Movie> Movies { get; set; }
}

和上下文:

public class MoviesContext : DbContext
{
    public DbSet<Movie> Movies { get; set; }
    public DbSet<Actor> Actors { get; set; }

    public MoviesContext()
    {
        Database.SetInitializer(new DropCreateDatabaseIfModelChanges<MoviesContext>());
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        modelBuilder.Entity<Movie>().
            HasMany(m => m.Actors).
            WithMany(a => a.Movies).
            Map(
                m =>
                {
                    m.MapLeftKey("MovieId");
                    m.MapRightKey("ActorId");
                    m.ToTable("ActorsMovies");
                });
    }
}

表“ActorsMovies”已在 sql server 上创建。如何使用实体框架将数据插入此表中?例如,要在电影表上插入数据,我使用了代码 db.Movies.Add(movie) 和 db.SaveChanges() }

4

1 回答 1

1
movie.Actors.Add(actor);
db.SaveChanges();

这应该允许您更新多对多表。

于 2013-03-12T22:08:06.630 回答