主细节外键插入

时间:2014-01-20 08:49:09

标签: c# entity-framework stored-procedures linq-to-sql foreign-keys

有两张桌子。

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-to-sql我试图将数据从winforms插入数据库。 在设计器中,我已经为我的存储过程设置了插入行为,类Customer和类Contact,但是在

_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.

我应该编辑我的存储过程还是在代码中处理它?<​​/ p>

如何在插入子行时设置Contacts.CustomerId

1 个答案:

答案 0 :(得分:0)

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

DataClasseseMyDataContext db = new DataClasseseMyDataContext(conString);

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

db.SubmitChanges();

您必须在表之间创建关系并将它们添加到DBML