In this question: Ef Many To Many , there was an answer on how to manually specify a link table. But I have a slightly unique situation (which, I'm sure, is not unique).
My two tables have an Id field. EG: [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 table is [dbo].[AccountsToPersons]... has EG fields: [AccountId] and [PersonId]
The AccountsToPersons table is not represented by a class in code.
I obviously already have an existing model, but we use the EF Code-First Fluent API instead of updating the model from the database.
So, how do I change this code to work with displaying different identifier column 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");
When starting a basic Linq To EF query (from x in context.Accounts select x).ToList(); The request fails with the following error:
- "Invalid column name Person_Id."
But when you run Query (from x in context.Persons select x).ToList(); I do not get errors.
Besides the basic typed columns, my models 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 note that although my Accounts request passes and contains information about the field, the Persons field is always null, although I'm sure there are links in my AccountsToPersons table.