实体框架代码优先 - 外键非主键字段 [英] Entity Framework Code First - Foreign Key to non primary key field

查看:400
本文介绍了实体框架代码优先 - 外键非主键字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有看起来像这样的两个表:

  dbo.ReviewType 
ReviewTypeId INT PRIMARY KEY
SHORTNAME CHAR(1) - 唯一索引
说明

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

回顾总是有一个ReviewType。结果
一ReviewType可有许多评论有关。



我无法使用代码首先流利的API中的实体框架映射这一点。
现在看来似乎不使用不映射到主键的外键喜欢我。我使用的外键唯一约束/索引,而不是主键。



如何正确实体框架中使用C#映射呢?



我要指出,我现在正在做的方式是给我这个错误:




System.Data.Edm.EdmAssociationConstraint:该类型的引用约束的从属角色所有属性必须是相同的主体作用相应的属性类型。该类型的实体审查财产ReviewTypeCode的不匹配的属性的类型'ID'对实体'的引用约束'ReviewType_ReviewsReviewType。



解决方案

EF的当前版本不支持唯一索引,并且基于非主唯一键不能映射关系。


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

解决方案

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

这篇关于实体框架代码优先 - 外键非主键字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆