7

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

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Dismissile
  • 32,564
  • 38
  • 174
  • 263
  • 1
    why would you opt for such an approach? adding a FK for ReviewTypeId instead of ShortName will solve your problem. – Pedro Costa Sep 20 '11 at 17:10
  • Because it's beyond my control. I realize it might not be the best solution but I didn't design the database. I'm trying to map the models using an existing schema usent the Fluent API. – Dismissile Sep 20 '11 at 17:30

1 Answers1

6

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

Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • Is this still the case? I have read an article http://blogs.southworks.net/dschenkelman/2012/08/18/creating-indexes-via-data-annotations-with-entity-framework-5-0/ which helped me get unique indexes. However it could not create relationship based on the unique keys. Isn't there a new version of EF coming up that supports this? – Mounhim Feb 20 '13 at 23:51