Search code examples
.net-coreentity-framework-coremany-to-manyef-fluent-api

ManyToMany Relation in EF Core fluent API


I'm facing with a probleme in entity framework Core with fluent API.

I Want to configure a Many to many relation dynamically so I used the following code :

    var relationEntityBuilder = entityTypeBuilder1.HasMany(lambdaManyFirst)
                       .WithMany(lambdaManySecond).UsingEntity(j => j.ToTable(attribute.RelationTableName))

It almost works but i still have a problem with ForeignKey.

By default EF try to make it with columns named "ObJect1sId" and "Object2sId" but in my case the foreign key columns are named "IdObject1" and "IdObject2".

How can I change foreigne key column name??

thank you.


Solution

  • You need to use some of the other UsingEntity overloads which allow you to configure the left and right navigations.

    For instance

    entityTypeBuilder1
        .HasMany(lambdaManyFirst)
        .WithMany(lambdaManySecond)
        .UsingEntity<Dictionary<string, object>>(joinEntityName,
            j => j.HasOne<TEntity2>().WithMany().HasForeignKey(fkName2),
            j => j.HasOne<TEntity1>().WithMany().HasForeignKey(fkName1),
            j => j.ToTable(joinTableName)
        );