EF Fluent API Many To Many with different ID Field Names

一曲冷凌霜 提交于 2019-12-05 08:35:28

Try adding p => p.Accounts to your WithMany clause:

modelBuilder.Entity<Account>()
  .HasMany(a => a.Persons)
  .WithMany(p => p.Accounts) // <-- I think this should fix it
  .Map(x =>
  {
    x.MapLeftKey("AccountId"); // <-- Account.Id to AccountsToPersons.AccountId??
    x.MapRightKey("PersonId"); // <-- Person.Id  to AccountsToPersons.PersonId??
    x.ToTable("AccountsToPersons");
  });

I just built up a test solution for your problem and for me it looks that is working.

One thing that i see you did different than me is:

public IList<Person> Persons { get; set; } // <-- in the Account model
public IList<Account> Accounts { get; set; } // <-- in the Person model

Try modifying into this:

public DbSet<Person> Persons { get; set; }
public DbSet<Account> Accounts { get; set; }

If this doesn't work i`ll post my entire setup.

My structure looks like this and it works for the queries you displayed:

public class Person
{
    public int ID { get; set; }

    public string Name { get; set; }

    public IList<Account> Accounts { get; set; }
}

public class Account
{
    public int ID { get; set; }

    public string Name { get; set; }

    public IList<Person> Persons { get; set; }
}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public DbSet<Account> AccountSet { get; set; }

    public DbSet<Person> PersonSet { get; set; }

    public ApplicationDbContext()
        : base("DefaultConnection")
    {
        this.Database.Log = (msg) => { Debug.Write(msg); };
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

        modelBuilder.Entity<Account>().HasKey(x => x.ID);
        modelBuilder.Entity<Person>().HasKey(x => x.ID);

        modelBuilder.Entity<Account>()
            .HasMany(a => a.Persons)
            .WithMany()
            .Map(w =>
            {
                w.MapLeftKey("AccountId");
                w.MapRightKey("PersonId");
                w.ToTable("AccountsToPersons");
            });
    }
}

Have you tried modifying your AccountsToPersons mapping slightly:

 modelBuilder.Entity<Account>()
   .HasMany(a => a.Persons)
   .WithMany(p => p.Accounts) <-- Change
   .Map(x =>
    {
         x.MapLeftKey("AccountId"); // <-- Account.Id to AccountsToPersons.AccountId??
         x.MapRightKey("PersonId"); // <-- Person.Id  to AccountsToPersons.PersonId??
         x.ToTable("AccountsToPersons");
    });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!