我在添加外鍵到表列時出現問題。 我的表格是這樣看的。我需要在UserProfile
表如何通過添加外鍵在Visual Studio 2012中引用兩個表?
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)
);
我添加了一個外鍵從Contact
表引用ContactOwnerId
到UserId
,但似乎,不正確的,因爲用戶ID被高亮顯示,給錯誤:
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關聯,以便聯繫人可以與一個特定用戶相關聯。
好的,謝謝,sgeddes你的答案 –
@KirillRyzhkov - NP,很高興我能幫忙。 – sgeddes