0

有两个表。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

+0

你为什么插入与'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主键。 –

+0

我已经从示例Northwind存储过程创建了该存储过程。你能解释我插入后选择CustomerId有什么问题吗?另外,我应该有一个存储过程使用@@ IDENTITY,但如果保存我需要在不同的子表中插入许多子行,如联系人,项目等。 – Carlo

+0

程序'InsertCustomers'。第一条语句看起来像主键是auto-inc,但是您传递的是customerid作为参数。我认为你应该将customerid定义为输出参数。 SET @CustomerId = @@ IDENTITY' –

回答

0

您可以使用简单的Linq方法插入数据,而不是使用存储过程来插入数据。

DataClasseseMyDataContext db = new DataClasseseMyDataContext(conString); 

db.Customers.InsertOnSubmit(Customers); 
tblSupplierPO.tblInvSupplierPOPIDetails.Add(Contacts); 

db.SubmitChanges(); 

必须已创建表之间的关系并将其添加到DBML

+0

我怎么知道我是否需要更新或插入行。如何添加多个子行。例如,我需要同时插入一个具有三个联系人的客户。 – Carlo

+0

你可以有不同的方法来插入和更新 要插入多个细节,你可以有一个列表包含联系人Objects.By循环该列表,你可以插入多个细节,或者你可以插入所有细节atonce。 '列表 ContactList =您的联系人对象列表; foreach(联系人列表中的联系人c) { tblSupplierPO.tblInvSupplierPOPIDetails.Add(c); }' – tarzanbappa