EF core many to many configuration not working with Fluent API

后端 未结 3 1864
粉色の甜心
粉色の甜心 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条回答
  •  猫巷女王i
    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()
            .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.

提交回复
热议问题