Warm tip: This article is reproduced from serverfault.com, please click

Entity Framework Core Many to Many change navigation property names

发布于 2020-11-27 21:15:43

I have a table called "LogBookSystemUsers" and I want to setup many to many functionality in EF Core 5. I almost have it working but the problem is my ID columns are named SystemUserId and LogBookId but when EF does the join it tries to use SystemUserID and LogBookID. This is my current configuration code:

modelBuilder.Entity<SystemUser>()
            .HasMany(x => x.LogBooks)
            .WithMany(x => x.SystemUsers)
            .UsingEntity(x =>
            {
                x.ToTable("LogBookSystemUsers", "LogBooks");
            });

I tried this:

modelBuilder.Entity<SystemUser>()
            .HasMany(x => x.LogBooks)
            .WithMany(x => x.SystemUsers)
            .UsingEntity<Dictionary<string, object>>("LogBookSystemUsers",
                x => x.HasOne<LogBook>().WithMany().HasForeignKey("LogBookId"),
                x => x.HasOne<SystemUser>().WithMany().HasForeignKey("SystemUserId"),
                x => x.ToTable("LogBookSystemUsers", "LogBooks"));

But that just adds two new columns instead of setting the names of the current columns.

This is all database first. I don't want to have to use a class for the many to many table because I do this all over in my project and I don't want a bunch of useless classes floating around. Any ideas?

Questioner
GBreen12
Viewed
0
Ivan Stoev 2020-11-28 11:55:57

Interesting bug, consider posting it to EF Core GitHub issue tracker.

By idea what you have tried should do it

modelBuilder.Entity<SystemUser>()
    .HasMany(x => x.LogBooks)
    .WithMany(x => x.SystemUsers)
    .UsingEntity<Dictionary<string, object>>("LogBookSystemUsers",
        x => x.HasOne<LogBook>().WithMany().HasForeignKey("LogBookId"),
        x => x.HasOne<SystemUser>().WithMany().HasForeignKey("SystemUserId"),
        x => x.ToTable("LogBookSystemUsers", "LogBooks"));

And it works for any other FK property names except the {RelatedEntity}Id when related entity PK property is called ID.

As workaround until it gets fixed, define explicitly the desired join entity properties before configuring the relationship:


// add this
modelBuilder.SharedTypeEntity<Dictionary<string, object>>("LogBookSystemUsers", builder =>

{
    builder.Property<int>("LogBookId");
    builder.Property<int>("SystemUserId");
});
// same as the original
modelBuilder.Entity<SystemUser>()
    .HasMany(x => x.LogBooks)
    .WithMany(x => x.SystemUsers)
    .UsingEntity<Dictionary<string, object>>("LogBookSystemUsers",
        x => x.HasOne<LogBook>().WithMany().HasForeignKey("LogBookId"),
        x => x.HasOne<SystemUser>().WithMany().HasForeignKey("SystemUserId"),
        x => x.ToTable("LogBookSystemUsers", "LogBooks"));