Home > Back-end >  EF Core wrong Join entity type name
EF Core wrong Join entity type name

Time:02-24

I have three entities as shown here:

public class Application
{
    [Key]
    public int ApplicationId { get; set; }
    public string Name { get; set; }
    public virtual ICollection<User> Users { get; set; }
}

public class User
{
    [Key]
    public int UserId { get; set; }
    public string UserName { get; set; }
    public virtual ICollection<Application> Applications { get; set; }
}

Join entity

public class UserApplication
{
    public int UserId { get; set; }
    public int ApplicationId { get; set; }
    [ForeignKey("UserId")]
    public User User { get; set; }
    [ForeignKey("ApplicationId")]
    public Application Application { get; set; }
}

OnModelCreating section =>

modelBuilder.Entity<User>()
               .HasMany(x => x.Applications)
               .WithMany(x => x.Users)
               .UsingEntity(ua => ua.ToTable("UserApplication"));

modelBuilder.Entity<UserApplication>()
                .HasKey(a=> new { a.ApplicationId, a.UserId});

Running the code is causing an error

invalid object name => ApplicationUser.

Note - while OnModelCreating only entity with wrong name is there. DB Has table with name UserApplication

enter image description here

CodePudding user response:

You are using mixture of explicit and implicit join entity. I'm afraid EF Core assumes 2 separate many-to-many relationships with 2 separate tables. Note that by convention the implicit join entity name is {Name1}{Name2} with names being in ascending order, which in your case is ApplicationUser.

What you need is to use the the generic overload of UsingEntity fluent API and pass the explicit join entity type as generic type argument. Also configure the join entity there instead of separately. e.g.

modelBuilder.Entity<User>()
    .HasMany(x => x.Applications)
    .WithMany(x => x.Users)
    .UsingEntity<UserApplication>(
        //             ^^^
        ua => ua.HasOne(e => e.Application).WithMany().HasForeignKey(e => e.ApplicationId),
        ua => ua.HasOne(e => e.User).WithMany().HasForeignKey(e => e.UserId),
        ua =>
        {
            ua.ToTable("UserApplication");
            ua.HasKey(a => new { a.ApplicationId, a.UserId });
        });

  • Related