实体框架 - 一对一关系,一端不是主键
我想在实体框架数据模型中定义一种一对一的关系,一端作为一个表的主键,另一端作为另一个表的外键。例如:
table: aspnet_Users
w/ col: UserId guid Primary Key
对于与 User 表的 AspUserId 列相关的 aspnet_Users 表的 UserId 属性:
table: User
w /col: UserId int Primary Key
w /col: AspUserId guid
当我尝试执行此操作时,我收到一条错误消息,指出由于 AspUserId 字段不是其表的主键,因此无法工作:
错误 21 错误 113:多重性在关系“FK_User_aspnet_Users”中的角色“用户”中无效。由于从属角色属性不是关键属性,因此从属角色的重数上限必须为*。
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 *.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
外键需要映射到主键。否则,可能会发生以下记录:
这没有意义 - 并且会破坏您的 1-1 基数。
然而 - 话虽这么说(看看旧的会员数据库 - 恶心),
dbo.aspnet_Users
上的UserId
字段是主键。您确定您的外键位于正确的表上吗?您数据库上的
dbo.aspnet_Users
是否具有UserId
的 PK。另外 - 尽量不要绘制会员表 - 这将是一个痛苦的世界。成员资格模式中的关系非常复杂。
只需映射您自己的用户表即可。使用 FK 来进行数据库端工作(审计、存储过程、触发器等)是很好的。
但从模型方面来看,您应该通过 EF 与您的 User 实体进行交互,并通过 Membership Provider API 与您的 aspnet_Users (Membership) 实体进行交互。
如果您需要在代码中将它们“缝合在一起”(通常是这种情况),那么请将其封装在服务后面。
Foreign keys need to map to primary keys. Otherwise, the below records could happen:
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 ondbo.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 forUserId
.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.
用户表响应海报:
In response to a poster the User table: