If I want to have two tables with many-to-many relationship, how do I create models and seed the database?
For example classic tables Actors and Movies. I tried it like this
public class Actor
{
public Actor()
{
this.Movies = new HashSet<Movies>;
}
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set;}
public virtual ICollection<Movie> Movies { get; set; }
}
public class Movie
{
public Movie()
{
this.Actors = new HashSet<Actors>;
}
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Actor> Actors { get; set; }
}
As I understood Entity Framework creates automatically new table ActorMovies with two columns with IDs of Actor and Movie.
How I seed it:
Actor actor = new Actor { Name="John", Surname="Doe" };
Movie movie = new Movie { Name="John Doe and his garden hoe" };
actor.Movies.Add(movie);
dbContext.Add(movie); ( call from separate repository )
This automatically seeds Actor table as well and pretty much duplicates all data in both tables. Every time I add new Actor with same Movie, it creates new row in Movie table with same Name but just different ID, which is completely wrong.
My ApplicationDbContext is standard :
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
public DbSet<Actor> Actors { get; set; }
public DbSet<Movie> Movies { get; set; }
}
So what is the proper way of creating, initializing and seeding many-to-many relationship?