Sua*_*ere 5 c# entity-framework ef-fluent-api
在这个问题:Ef Many To Many,一个关于如何手动指定链接表的答案.但我有一个稍微独特的情况(我肯定不是真的很独特).
我的两个表都有一个Id字段.EG:[dbo].[Account].[Id]和[dbo].[Person].[Id].我的Code-First中的每个表都有以下OnModelCreating:
modelBuilder.Entity<Account>.HasKey(x => x.Id);
modelBuilder.Entity<Person>.HasKey(x => x.Id);
Run Code Online (Sandbox Code Playgroud)
但我的[dbo].[AccountsToPersons]...桌子有EG:[AccountId]和[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");
});
Run Code Online (Sandbox Code Playgroud)
运行基本的Linq To EF Query时(from x in context.Accounts select x).ToList();,查询失败并显示以下错误:
但是在运行Query时(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
Run Code Online (Sandbox Code Playgroud)
请注意,即使我的帐户查询通过并具有字段信息,该Persons字段始终为空,即使我确定我的AccountsToPersons表中有链接.
尝试添加p => p.Accounts到您的WithMany条款:
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");
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2823 次 |
| 最近记录: |