1

I have the model:

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; }
}

and the context:

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");
                });
    }
}

The table "ActorsMovies" is already created on sql server. how do I insert data into this table with entity framework? To insert data on the table Movies, for example, i've used the code db.Movies.Add(movie) and db.SaveChanges() }

1
  • so all your model is DB first? Commented Mar 12, 2013 at 22:07

1 Answer 1

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

This should allow you to update the many to many table.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.