In this question: Ef Many To Many, an answer came up on how to manually specify a linking table. But I have a slightly unique situation (which I'm sure isn't really unique).
My two tables each have an Id field. E.G.: [dbo].[Account].[Id]
and [dbo].[Person].[Id]
. Each of these tables in my Code-First has the following OnModelCreating:
modelBuilder.Entity<Account>.HasKey(x => x.Id);
modelBuilder.Entity<Person>.HasKey(x => x.Id);
But my [dbo].[AccountsToPersons]...
table has fields E.G.: [AccountId]
and [PersonId]
The AccountsToPersons table is not represented by a class in code.
I obviously already have an existing Model, but we are using EF Code-First Fluent API instead of updating model from database.
So how do I change this code to make it work with mapping different ID columns names?
public DbSet<Person> Persons { get; set; }
public DbSet<Account> Accounts { get; set; }
. . .
modelBuilder.Entity<Account>()
.HasMany(a => a.Persons)
.WithMany()
.Map(x =>
{
x.MapLeftKey("AccountId"); // <-- Account.Id to AccountsToPersons.AccountId??
x.MapRightKey("PersonId"); // <-- Person.Id to AccountsToPersons.PersonId??
x.ToTable("AccountsToPersons");
});
When running a basic Linq To EF Query (from x in context.Accounts select x).ToList();
, the query fails with the following error:
- "Invalid Column Name 'Person_Id'."
But when running the Query (from x in context.Persons select x).ToList();
, I get no error.
Other than basic typed columns, my models have these added to them:
// In my Account Model, I also have this property:
public IList<Person> Persons { get; set; }
// In my Person Model, I also have this property:
public IList<Account> Accounts { get; set; } // <-- in the Person model
And please note that even though my Accounts query passes and has field information, the Persons
field is always null, even though I'm sure there are links in my AccountsToPersons
table.