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
You should add the Clients property to the Job class too:
public class Job : IEntityBase
{
public int Id { get; set; }
public ICollection<Client> Clients{ get; set; }
}
Then everything should be in order.
For EF Core 5.0 and up, you may (finally) use direct relationships for many-to-many:
modelBuilder
.Entity<Post>()
.HasMany(p => p.Tags)
.WithMany(p => p.Posts)
.UsingEntity(j => j.ToTable("PostTags"));
Source: Relationships - EF Core | Microsoft (many-to-many)
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<ClientsJobs>()
.HasKey(x => new { x.ClientId, x.JobId });
modelBuilder.Entity<ClientsJobs>()
.HasOne(x => x.Client)
.WithMany(y => y.Jobs)
.HasForeignKey(y => y.JobId);
modelBuilder.Entity<ClientsJobs>()
.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.