首页 > 解决方案 > 名称不匹配时的实体框架外键

问题描述

我有一个表AccountValues,我想从我的Account表中引用它。但是,与其使用AccountValuesIdand AccountValues,我希望它通过以下前缀更具描述性MostRecent_

[ForeignKey("AccountValues")]
public long MostRecent_AccountValuesId { get; set; }
public AccountValues MostRecent_AccountValues { get; set; }

我的问题是我应该在哪里放置我的ForeignKey属性,以便我最终得到一个实际的外键(例如FK_Something)并且还可以MostRecent_AccountValues自动工作?

注意:我的约定是不要有复数表名。但是这里AccountValues是复数只是因为每一行都有许多不同的值。

标签: c#entity-frameworkef-code-first

解决方案


问题出在你的ForeignKey名字上public long MostRecent_AccountValuesIdForeignKey名称应与导航属性名称匹配,如下所示:

[ForeignKey("MostRecent_AccountValues")] // <-- Here it is
public long MostRecent_AccountValuesId { get; set; }
public AccountValues MostRecent_AccountValues { get; set; }

推荐阅读