I'm trying to configure many-to-many relationship in Entity Core, based on that discussion:
https://github.com/aspnet/EntityFrameworkCore/issues/1368
After configuration database is created, with extra column (ProducerId in Movies table), as shown here: Movies. On other side relationship in Producers table, there is no additional column, as shown here: Producers
In project I have classes:
public class Movie
{
public int Id { get; private set; }
public string Title { get; set; }
public Person Director { get; set; }
public TypesOfGenre Genre { get; set; }
public long Length { get; set; }
public DateTime Year { get; set; }
public Country CountryName { get; set; }
public IList<Person> Actors { get; set; }
//Configure enity:
public int DirectorId { get; set; }
public Country Country { get; set; }
public IList<MovieProducer> MovieProducers { get; set; }
}
public class Producer
{
public int Id { get; private set; }
public string CompanyName { get; set; }
public DateTime YearEstablished { get; set; }
public long EstimatedCompanyValue { get; set; }
public IList<Movie> Movies { get; set; }
//Configure enity:
public Country Country { get; set; }
public IList<MovieProducer> MovieProducers { get; set; }
}
And I have joinig tabe:
public class MovieProducer
{
public int ProducerId { get; set; }
public Producer Producer { get; set; }
public int MovieId { get; set; }
public Movie Movie { get; set; }
}
All entities are configured in DbContext class including joining table:
public void Configure(EntityTypeBuilder<MovieProducer> builder)
{
builder.HasKey(k => new { k.ProducerId, k.MovieId });
builder.HasOne(m => m.Movie)
.WithMany(mp => mp.MovieProducers)
.HasForeignKey(m => m.MovieId);
builder.HasOne(p => p.Producer)
.WithMany(mp => mp.MovieProducers)
.HasForeignKey(p => p.ProducerId);
}
What is wrong with this configuration to create many to many relationship? There should be no extra column for ProducerId in Movies table.
IList<Movie>
left in the Producer class effectively introduces another one-to-many. That is whyProducerId
is added to the Movie table. - Dimitar