【发布时间】:2014-01-20 08:49:08
【问题描述】:
有两张桌子。
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 插入数据库。 在设计器中,我已经为我的存储过程设置了插入行为,客户类和联系人类,但是在
_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 (technet.microsoft.com/en-us/library/ms187342.aspx) 或 SCOPE_IDENTITY() (technet.microsoft.com/en-us/library/ms190315.aspx) 方法。假设Customers表有一个 auto-inc 主键。 -
我已经从示例 Northwind 存储过程创建了该存储过程。你能解释一下插入后选择 CustomerId 有什么问题吗?另外,我应该有一个存储过程来使用@@IDENTITY,但是如果保存时我需要在不同的子表(如联系人、项目等)中插入许多子行。
-
程序
InsertCustomers。第一条语句看起来主键是 auto-inc,但您将 customerid 作为参数传递。我认为您应该将 customerid 定义为输出参数。SET @CustomerId = @@IDENTITY
标签: c# entity-framework stored-procedures linq-to-sql foreign-keys