I am having trouble with understanding and implementing a many to many repationship using the FLuent API and EF Core.
I have looked at this question and set up my relati
The Fluent API example you are trying to implement comes from EF 6. Many-to-Many relationship configuration is a little different in EF Core. For a start, you need to include an entity to represent the join/bridging table:
public class ClientsJobs
{
public int ClientId { get; set; }
public int JobId { get; set; }
public Client Client { get; set; }
public Job Job { get; set; }
}
Then you configure it like this in the OnModelCreating method:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity()
.HasKey(x => new { x.ClientId, x.JobId });
modelBuilder.Entity()
.HasOne(x => x.Client)
.WithMany(y => y.Jobs)
.HasForeignKey(y => y.JobId);
modelBuilder.Entity()
.HasOne(x => x.Job)
.WithMany(y => y.Clients)
.HasForeignKey(y => y.ClientId);
}
See more about it here: http://www.learnentityframeworkcore.com/configuration/many-to-many-relationship-configuration
Note: you do need to include navigational properties for both ends of the relationship in the related classes, so you need to add a Clients
property to your Job
entity.