问题
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'.
回答1:
Current version of EF doesn't support unique indexes and it cannot map relations based on non primary unique keys.
来源:https://stackoverflow.com/questions/7488300/entity-framework-code-first-foreign-key-to-non-primary-key-field