当前位置: 首页 > 编程语言 > C#

EFFluentAPImany-to-manywithdifferentIDfieldnames分享

时间:2023-04-10 20:03:59 C#

本题EFFluentAPImany-to-manywithdifferentIDfieldnames:EfManyToMany,如何手动指定的答案链接表。但是我有一个稍微独特的情况(我敢肯定不是很独特)。我的两个表都有一个Id字段。例如:[dbo].[帐户].[Id]和[dbo].[人].[Id]。我的Code-First中的每个表都有以下OnModelCreating:modelBuilder.Entity.HasKey(x=>x.Id);modelBuilder.Entity.HasKey(x=>x.Id);但是我的[dbo]。[AccountsToPersons]...表包含字段EG:[AccountId]和[PersonId]AccountsToPersons表未由代码中的类表示。我显然已经有了一个现有模型,但我们使用EFCode-FirstFluentAPI而不是从数据库更新模型。那么我该如何更改此代码以使用映射不同的ID列名称呢?publicDbSetPersons{get;放;}公共DbSet帐户{get;放;}。..模型构建器。(“帐户ID”);//<--Account.Id到AccountsToPersons.AccountId??x.MapRightKey("PersonId");//<--Person.Id到AccountsToPersons.PersonId??x.ToTable("AccountsToPersons");});运行基本的LinqToEF查询时(从context.Accounts中的x选择x).ToList();,查询失败并出现以下错误:但是在运行查询时(来自上下文中的x.Personsselectx).ToList();,我没有看错。除了基本类型的列之外,我的模型还添加了以下内容://在我的账户模型中,我还有这个属性:publicIListPersons{get;放;}//在我的个人模型中,我也有这个属性:publicIListAccounts{get;放;}//<--在Person模型中请注意,即使我的Accounts查询通过并包含字段信息,Persons字段始终为空,即使我确定AccountsToPersons表中有一个链接。尝试将p=>p.Accounts添加到WithMany子句:modelBuilder.Entity().HasMany(a=>a.Persons).WithMany(p=>p.Accounts)//{x.MapLeftKey("AccountId");//我刚刚为你的问题构建了一个测试解决方案,它似乎对我有用。我看到你做的与我不同的一件事是:publicIListPersons{get;放;}//尝试更改为:publicDbSetPersons{get;放;}公共DbSet帐户{get;放;如果这不起作用,我将发布我的整个设置。我的结构看起来像这样,适用于您显示的查询:publicclassPerson{publicintID{get;放;}公共字符串名称{得到;放;}publicIListAccounts{get;放;}}publicclass}publicstringName{get;放;}publicIListPersons{get;放;}}publicclassApplicationDbContext:IdentityDbContext{publicDbSetAccountSet{get;放;}publicDbSetPersonSet{得到;放;}publicApplicationDbContext():base("DefaultConnection"){this.Database.Log=(msg)=>{Debug.Write(msg);};}protectedoverridevoidOnModelCreating(DbModelBuildermodelBuilder){base.OnModelCreating(modelBuilder);modelBuilder.Conventions.Remove();modelBuilder.Entity().HasKey(x=>x.ID);modelBuilder.Entity().HasKey(x=>x.ID);modelBuilder.Entity()。HasMany(a=>a.Persons).WithMany().Map(w=>{w.MapLeftKey("AccountId");w.MapRightKey("PersonId");w.ToTable("AccountsToPersons");});有没有试过稍微修改一下AccountsToPersons的映射:以上是C#学习教程:EFFluentAPImultiplepairs有许多不同的ID字段名称来共享所有内容。如果对大家有用,需要进一步了解C#学习教程,希望大家多多关注—modelBuilder.Entity().HasMany(a=>a.Persons).WithMany(p=>p.Accounts){x.MapLeftKey("AccountId");//本文摘自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: