INSERT语句与FOREIGN KEY约束冲突

时间:2013-05-26 09:52:41

标签: sql sql-server database ado.net

我搜索了这类问题,但遗憾的是没有找到任何解决方案。

当我尝试在我的应用程序中创建联系人时出现错误

  

INSERT语句与FOREIGN KEY约束“FK_Contacts_UserProfile”冲突。冲突发生在数据库“ContactAppContext”,表“dbo.UserProfile”,列'UserId'。

我想将UserIdContacts

相关联

我的表格如下:

CREATE TABLE [dbo].[Contacts] (
    [ContactId] INT            IDENTITY (1, 1) NOT NULL,
    [UserId]    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 [dbo].[UserProfile] ([UserId])
);

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表格中存在UserProfile

pic

那么我做错了什么?

编辑1
@Alexander Fedorenko
你的意思是这段代码?

SET IDENTITY_INSERT [dbo].[UserProfile] ON
INSERT INTO [dbo].[UserProfile] ([UserId], [UserName]) VALUES (1, N'admin')
INSERT INTO [dbo].[UserProfile] ([UserId], [UserName]) VALUES (2, N'test')
INSERT INTO [dbo].[UserProfile] ([UserId], [UserName]) VALUES (3, N'user')
SET IDENTITY_INSERT [dbo].[UserProfile] OFF

@Sachin我怎样才能确定,当我尝试在Contact表中插入时,它应该出现在UserProfile表中?我有一个UserId = 3的用户登录,当他插入数据时,创建的联系人将与该用户有关。

编辑2
因此,当我在视图中为UserId创建一个编辑器字段时,它似乎正在工作,当我指定UserId时,数据已创建,但我不希望此编辑器字段用于{存在“创建联系人”页面中的{1}},因为用户编写他的UserId不方便。因此可以将UserId与登录用户相关联,例如,当他创建数据时,他不需要指定他的UserId,而是记录将自动保存到数据库中,并带有他的ID ?

2 个答案:

答案 0 :(得分:2)

您需要先将数据添加到UserProfile表,或者在插入数据时临时禁用外键约束。

您的表已设置为Contact表引用UserProfile表,因此需要在UserProfile中输入以插入联系人。

以这种方式看待:如果你不首先在UserProfile表中生成它,你怎么知道要在Contacts表中输入的UserID是什么?

答案 1 :(得分:0)

首先尝试创建UserProfile表,然后创建Contacts表。

相关问题