在这个问题中:Ef 多对多 https://stackoverflow.com/questions/8927278/how-to-configure-many-to-many-relationship-using-entity-framework-fluent-api,关于如何手动指定链接表的答案出现了。但我有一个稍微独特的情况(我确信这并不是真正独特)。
我的两个表都有一个 Id 字段。例如。:[dbo].[Account].[Id]
and [dbo].[Person].[Id]
。我的 Code-First 中的每个表都有以下 OnModelCreating:
modelBuilder.Entity<Account>.HasKey(x => x.Id);
modelBuilder.Entity<Person>.HasKey(x => x.Id);
But my [dbo].[AccountsToPersons]...
表有字段例如:[AccountId]
and [PersonId]
AccountsToPersons 表不是由代码中的类表示。
我显然已经有一个现有模型,但我们使用 EF Code-First Fluent API,而不是从数据库更新模型。
那么如何更改此代码以使其能够映射不同的 ID 列名称呢?
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");
});
运行基本 Linq To EF 查询时(from x in context.Accounts select x).ToList();
,查询失败并出现以下错误:
但是当运行查询时(from x in context.Persons select x).ToList();
,我没有收到任何错误。
除了基本的类型列之外,我的模型还添加了以下内容:
// 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
请注意,即使我的帐户查询通过并具有字段信息,Persons
字段始终为空,即使我确定我的中存在链接AccountsToPersons
table.