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

限于喜欢 提交于 2019-12-13 12:08:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!