实体框架 - 1对1的关系,其中一端是不是主键 [英] Entity Framework - 1 to 1 relationship where one end is not a primary key
问题描述
我想限定在实体框架的数据模型,该模型是1对1的一端为一个表中的主键,另一端上的另一个的外键关系。例如:
表:aspnet_Users
W /西:用户ID GUID主键
与aspnet_Users表格内与用户表的AspUserId列的用户ID属性:
表:用户
W /西:用户ID int主键
W /西:AspUserId GUID
当我尝试这样做,我得到一个错误,指出由于AspUserId字段不是它的一个主键的表,该表将无法工作:
错误21错误113:多重不在角色用户的关系FK_User_aspnet_Users有效。因为从属角色属性不是关键性质,上限从属作用的多重性必须*。
外键需要映射到主键。否则,下面的记录可能发生:
aspnet_Users
用户帐号
11111111
11111111
22222222
用户
用户ID AspUserId
1 11111111
2 11111111
这没有任何意义 - 而伤了你的1-1基数
不过 - 他这样说(看着一个老成员DB - 呸),用户ID
字段 dbo.aspnet_Users
是的主键。
你确定你有你在正确的表的外键?请问 dbo.aspnet_Users
您的数据库有PK的用户ID
。
此外 - 尽量不要映射成员表 - 这将是一个痛苦的世界。在会员架构的关系的高度复杂的的。
刚刚绘制自己的用户表。它的优良有FK的数据库方面的工作(审计,存储过程,触发器等)。
不过,从模型边 - 你应该通过成员资格提供API通过EF您的用户实体,你aspnet_Users(会员)实体交互
如果您需要在code(通常情况下)缝合在一起,然后封装背后的服务。
I'd like to define a relationship in an Entity Framework data model that is 1-to-1 with one end as a primary key of one table and the other end a foreign key on another. For instance:
table: aspnet_Users
w/ col: UserId guid Primary Key
with the UserId property of the aspnet_Users table related to the AspUserId column of the User table:
table: User
w /col: UserId int Primary Key
w /col: AspUserId guid
When I try to do this I get an error saying that since the AspUserId field is not a primary key of it's table that won't work:
Error 21 Error 113: Multiplicity is not valid in Role 'User' in relationship 'FK_User_aspnet_Users'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be *.
Foreign keys need to map to primary keys. Otherwise, the below records could happen:
aspnet_Users
UserId
11111111
11111111
22222222
User
UserId AspUserId
1 11111111
2 11111111
And that doesn't make sense - and breaks your 1-1 cardinality.
However - that being said (looking at an old membership db - yuck), UserId
field on dbo.aspnet_Users
is a primary key.
Are you sure you have your foreign key on the correct table? Does dbo.aspnet_Users
on your database have the PK for UserId
.
Also - try not to map the membership tables - it will be a world of pain. The relationships in the membership schema are highly complicated.
Just map your own User table. It's fine to have the FK for database-side work (auditing, stored procedures, triggers, etc).
But from the model side - you should be interacting with your User entity via EF, and your aspnet_Users (Membership) entity via the Membership Provider API.
If you need to "stitch them together" in your code (often the case), then encapsulate that behind a service.
这篇关于实体框架 - 1对1的关系,其中一端是不是主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!