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.

1 Answer 1

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)
    );
3
  • 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, 2021 at 8: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, 2021 at 9:08
  • @Ivan filter is not working in many to many relationship..can u pls check stackoverflow.com/questions/65804252/…
    – Ajt
    Jan 20, 2021 at 7:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.