Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Code First - Foreign Key to non primary key field

I have two tables that look like this:

dbo.ReviewType
    ReviewTypeId INT PRIMARY KEY
    ShortName CHAR(1) - Unique Index
    Description

dbo.Review
   ReviewId INT PRIMARY KEY
   ReviewType_ShortName CHAR(1) - FK to ReviewType
   ...

A Review always has a ReviewType.
A ReviewType can be associated with many reviews.

I'm having trouble mapping this in Entity Framework using the Code First Fluent API. It seems like it does not like me using a foreign key that doesn't map to the Primary Key. I'm using a foreign key to a Unique Constraint/Index instead of to the Primary Key.

How can I map this properly in Entity Framework using C#?

I should note that the way I am doing it right now is giving me this error:

System.Data.Edm.EdmAssociationConstraint: : The types of all properties in the Dependent Role of a referential constraint must be the same as the corresponding property types in the Principal Role. The type of property 'ReviewTypeCode' on entity Review' does not match the type of property 'Id' on entity 'ReviewType' in the referential constraint 'ReviewType_Reviews'.

like image 331
Dismissile Avatar asked Sep 20 '11 16:09

Dismissile


1 Answers

Current version of EF doesn't support unique indexes and it cannot map relations based on non primary unique keys.

like image 159
Ladislav Mrnka Avatar answered Oct 10 '22 06:10

Ladislav Mrnka