问题
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 *.
回答1:
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.
回答2:
In response to a poster the User table:
CREATE TABLE [dbo].[User](
[UserId] [int] IDENTITY(1,1) NOT NULL,
[AspUserId] [uniqueidentifier] NOT NULL,
[ModifiedDate] [datetime] NOT NULL,
[CreatedDate] [datetime] NOT NULL,
CONSTRAINT [PK_User] PRIMARY KEY CLUSTERED
(
[UserId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[User] WITH CHECK ADD CONSTRAINT [FK_User_aspnet_Users] FOREIGN KEY([AspUserId])
REFERENCES [dbo].[aspnet_Users] ([UserId])
GO
ALTER TABLE [dbo].[User] CHECK CONSTRAINT [FK_User_aspnet_Users]
GO
来源:https://stackoverflow.com/questions/4485350/entity-framework-1-to-1-relationship-where-one-end-is-not-a-primary-key