有两个表。Master-detail外键插入
Customer Contact
_______________________________________
CustomerId *--> CustomerId
CustomerName ContactId
... ContactFirstName
...
One customer can have many contacts
存储过程
CREATE PROCEDURE dbo.InsertCustomers
(
@CustomerId int,
@CustomerName nvarchar(50)
)
AS
SET NOCOUNT OFF;
INSERT INTO [dbo].[Customers] ([CustomerName]) VALUES (@CustomerName);
SELECT CustomerId, CustomerName FROM Customers WHERE (CustomerId = @CustomerId)
第二个:
CREATE PROCEDURE dbo.InsertContacts
(
@CustomerId int,
@ContactFirstName nvarchar(20)
)
AS
SET NOCOUNT OFF;
INSERT INTO [dbo].[Contacts] ([CustomerId], [ContactFirstName]) VALUES (@CustomerId, @ContactFirstName);
SELECT ContactId, CustomerId, ContactFirstName FROM Contacts WHERE (CustomerId = @CustomerId)
使用LINQ到SQL我试图从的WinForms数据插入到数据库中。 在设计师,我已经设置插入行为,我存储两个PROC,一流的客户和阶级联系,但
_context.SubmitChanges();
遇到错误
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_CustomerContact". The conflict occurred in database "test", table "dbo.Customers", column 'CustomerId'.The statement has been terminated.
应该修改我的存储过程或处理,在代码?
如何在插入子行时设置Contacts.CustomerId
。
你为什么插入与'CustomerName'然后选择用'CustomerId'一行一条记录?您可能会查找@@ IDENTITY(http://technet.microsoft.com/en-us/library/ms187342.aspx)或SCOPE_IDENTITY()(http://technet.microsoft.com/en-us/library /ms190315.aspx)方法。假设'Customers'表有一个auto-inc主键。 –
我已经从示例Northwind存储过程创建了该存储过程。你能解释我插入后选择CustomerId有什么问题吗?另外,我应该有一个存储过程使用@@ IDENTITY,但如果保存我需要在不同的子表中插入许多子行,如联系人,项目等。 – Carlo
程序'InsertCustomers'。第一条语句看起来像主键是auto-inc,但是您传递的是customerid作为参数。我认为你应该将customerid定义为输出参数。 SET @CustomerId = @@ IDENTITY' –