EF core many to many configuration not working with Fluent API

后端 未结 3 1854
粉色の甜心
粉色の甜心 2021-02-20 01:07

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

相关标签:
3条回答
  • 2021-02-20 01:11

    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.

    0 讨论(0)
  • 2021-02-20 01:23

    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)

    0 讨论(0)
  • 2021-02-20 01:24

    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.

    0 讨论(0)
提交回复
热议问题