Brian Rice
Brian Rice

Reputation: 3257

Entity Framework foreign key when name doesn't match

I have a table called AccountValues that I would like to reference from my Account table. However rather than using AccountValuesId and AccountValues, I would like it to be a little more descriptive by prefixing MostRecent_ as follows:

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

My question is where should I place my ForeignKey attribute, so that I end up with an actual foreign key (e.g. FK_Something) and also have MostRecent_AccountValues automagically work?

Note: my convention is not to have plural table names. But here AccountValues is plural only because each row has a number of different values in it.

Upvotes: 2

Views: 351

Answers (1)

TanvirArjel
TanvirArjel

Reputation: 32119

Problem is in your ForeignKey name on the public long MostRecent_AccountValuesId property. ForeignKey name should match the navigation property name as follows:

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

Upvotes: 3

Related Questions