EF流利的API多对多的不同ID字段名称

EF流利的API多对多的不同ID字段名称

本文介绍了EF流利的API多对多的不同ID字段名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这个问题:,一个答案来了个如何手动指定链接表。但我有一个轻微的独特情况(我敢肯定,是不是真的是唯一的)。

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).

我的两个表各有一个ID字段。 EG:。。 [DBO] [客户] [ID] [DBO] [人] [ID] 。每一个在我的代码,首先这些表的有以下OnModelCreating:

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);



但我的 [DBO]。[AccountsToPersons] ... 表有字段EG: [ACCOUNTID] [PERSONID]

AccountsToPersons表不是在代码中的类来表示。

The AccountsToPersons table is not represented by a class in code.

我明明已经有一个现成的模式,但我们使用EF代码优先流利的API,而不是更新的数据库模型。

I obviously already have an existing Model, but we are using EF Code-First Fluent API instead of updating model from database.

那么,如何改变这一代码,使其与映射不同的ID列名工作?

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");
  });

当运行一个基本的Linq到EF查询(从X在context.Accounts选择X).ToList(); ,查询失败,出现以下错误:

When running a basic Linq To EF Query (from x in context.Accounts select x).ToList();, the query fails with the following error:


  • 无效的列名PERSON_ID'。

但是(在context.Persons从X选择x)运行查询时。了ToList(); ,我没有得到任何错误

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

和请注意,即使我的账户查询传递并有现场资料,字段总是空的,即使我敢肯定有在我的链接 AccountsToPersons

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.

推荐答案

尝试添加 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");
  });

这篇关于EF流利的API多对多的不同ID字段名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 00:11