2

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.

Vince
  • 23
  • 4

1 Answers1

4

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)
    );
Ivan Stoev
  • 195,425
  • 15
  • 312
  • 343
  • 1
    Thank you it works for writting but i still have problem with reading. a litle corection to your post : an '>' is missing to close generic of UsingEntity. – Vince Jan 19 '21 at 08:44
  • Corrected. And yes, the configuration API is not quite intuitive/readable, but at least it exists :-) `j` here stands for "join entity", and first two lambdas configure the two many-to-one relationships from join entity to second/first involved entities. – Ivan Stoev Jan 19 '21 at 09:08
  • @Ivan filter is not working in many to many relationship..can u pls check https://stackoverflow.com/questions/65804252/ef-core-5-many-to-many-filter – Ajt Jan 20 '21 at 07:04