Search code examples
frameworksmany-to-manyentity

entity framework seed in OnModelCreating with many-to-many relatioship


i have 2 class with a many to many relationship

public class Actor
{
    public int Id { get; set; }
    public string Name { get; set; }

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

public class Movie
{
    public int Id { get; set; }
    public string Name { get; set; }

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

I would like to add data in the generated tables via the OnModelCreating.

I have always un error because actormovie don't exist at this time.

Might you help me ?


Solution

  • I found the solution on Join entity type configuration

    Use this to seed data OnModelCreating for the joining table:

    
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder
          .Entity<Actor>()
          .HasData(new Actor { Id = 1, Name = "Keanu Reeves" });
    
        modelBuilder
          .Entity<Movie>()
          .HasData(
                 new Movie { Id = 1, Name = "Matrix" }, 
                 new Movie { Id = 2, Name = "John Wick" });
    
        modelBuilder
          .Entity<Actor>()
          .HasMany(m => m.Movies)
          .WithMany(a => a.Actors)
          .UsingEntity(j => j
            .HasData(
                new { ActorsId = 1, MoviesId = 1 },
                new { ActorsId = 1, MoviesId = 2 } ));
    }
    

    This worked for me.