我在将外键添加到表列时遇到问题。我的桌子是这样的。我需要ContactOwnerId
从Contact
表UserId
中引用到UserProfile
表中
CREATE TABLE [dbo].[Contacts] (
[ContactId] INT IDENTITY (1, 1) NOT NULL,
[ContactOwnerId] INT NOT NULL,
[FirstName] NVARCHAR (MAX) NOT NULL,
[LastName] NVARCHAR (MAX) NOT NULL,
[Address] NVARCHAR (MAX) NOT NULL,
[City] NVARCHAR (MAX) NOT NULL,
[Phone] NVARCHAR (MAX) NOT NULL,
[Email] NVARCHAR (MAX) NOT NULL,
CONSTRAINT [PK_dbo.Contacts] PRIMARY KEY CLUSTERED ([ContactId] ASC),
CONSTRAINT [FK_Contacts_UserProfile] FOREIGN KEY ([UserId]) REFERENCES [Contacts]([ContactOwnerId])
);
CREATE TABLE [dbo].[UserProfile] (
[UserId] INT IDENTITY (1, 1) NOT NULL,
[UserName] NVARCHAR (56) NOT NULL,
PRIMARY KEY CLUSTERED ([UserId] ASC),
UNIQUE NONCLUSTERED ([UserName] ASC)
);
我添加了一个外键,但似乎不对,因为 UserId 突出显示,给出错误:
SQL71501 :: Foreign Key: [dbo].[FK_Contacts_UserProfile] has an unresolved reference to Column [dbo].[Contacts].[UserId].
SQL71516 :: The referenced table '[dbo].[Contacts]' contains no primary or candidate keys that match the referencing column list in the foreign key. If the referenced column is a computed column, it should be persisted.
如何正确引用这两个表?提前致谢。
编辑 我确实像sgeddes说的那样。但是当我尝试创建联系人时出现错误。INSERT 语句与 FOREIGN KEY 约束“FK_Contacts_UserProfile”冲突。冲突发生在数据库“ContactAppContext”、表“dbo.UserProfile”、列“UserId”中。该语句已终止。
如果我删除外键,我不会收到错误。
我想要实现的是,当用户创建联系人时,他的 Id(UserId) 可以与 ContactOwnerId 关联,以便联系人可以与一个特定用户相关联。