使用linq to sql将SP插入一对多表中

时间:2016-07-03 16:11:00

标签: sql sql-server linq-to-sql

我有第一张表<16:58:57> 8I <16:58:57> 8IIn <16:58:57> 8IInnc <16:58:57> 8IInncco <16:58:57> 8IInnccoom <16:58:57> 8IInnccoommi <16:58:57> 8IInnccoommiin <16:58:57> 8IInnccoommiinng <16:58:57> 8IInnccoommiinngg <16:58:57> 8IInnccoommiinngg C <16:58:57> 8IInnccoommiinngg CCo <16:58:57> 8IInnccoommiinngg CCoon <16:58:57> 8IInnccoommiinngg CCoonnn <16:58:57> 8IInnccoommiinngg CCoonnnne 和第二张表Customers(一对多),因此1家公司可能有超过1个主要联系人。

我为两个表创建了datacontext并创建了这个存储过程:

CustomerContact

现在我如何使用Linq-to-SQL将所有参数传递给SP我尝试过这段代码,但是显示错误

  

未提供CustomerID

当我从存储过程中使用CustomerID时。

CREATE PROCEDURE [dbo].[InsertNewCustomer]
    @CustoName VARCHAR (50),
    @Add1 VARCHAR (50),
    @Add2 VARCHAR (50),
    @City VARCHAR (50),
    @PostCOde VARCHAR (15),
    @County VARCHAR (30),
    @Country VARCHAR (30),
    @Rows int,
    @CustomerID INT,
    @Title VARCHAR(5),
    @FirstName VARCHAR(25),
    @LastName VARCHAR(25),
    @Designation VARCHAR(30),
    @LandLine VARCHAR(25),
    @Mobile VARCHAR(25),
    @Email VARCHAR(50),
    @FAX VARCHAR(25)
AS
    INSERT INTO Customers(CustName, Add1, Add2, City, PostCode, County, Country)
    VALUES(@CustoName, @Add1, @Add2, @City, @PostCOde, @County, @Country)

    SET @CustomerID = (SELECT MAX(@@IDENTITY) from Customers)

    WHILE @Rows IS NOT NULL
    BEGIN
        INSERT INTO CustomerContact(CustomerID, Title, FirstName, LastName, Designation, LandLine, Mobile, Email, FAX)
        VALUES(@CustomerID, @Title, @FirstName, @LastName, @Designation, @LandLine, @Mobile, @Email, @FAX)
    END

    RETURN 0

此外,我想将Rows参数传递给SP,它会将数据插入到客户中,但当它尝试插入到customercontact时,它会显示CustomerID的错误。

如果我尝试传递参数,它会在SP(InsertNewCustomer)名称下显示红线,所以我不确定我做错了什么。

Cust.CustName = companyName.Text;
Cust.Add1 = custAdd1txt.Text;
Cust.Add2 = custAdd2txt.Text;
Cust.City = custCitytxt.Text;
Cust.PostCode = custPostCodetxt.Text;
Cust.County = custCounty.Text;
Cust.Country = custCountry.Text;

custDC.Customers.InsertOnSubmit(Cust);
custDC.SubmitChanges();

for (int i = 0; i <= MyCustomers.RowCount - 1; i++)
{
    custCont.Title = custKeyContactGV["Title", i].Value.ToString();
    custCont.FirstName = custKeyContactGV["FirstName", i].Value.ToString();
    custCont.LastName = custKeyContactGV["LastName", i].Value.ToString();
    custCont.Designation = custKeyContactGV["Designation", i].Value.ToString();
    custCont.LandLine = custKeyContactGV["Landline", i].Value.ToString();
    custCont.Mobile = custKeyContactGV["Mobile", i].Value.ToString();
    custCont.Email = custKeyContactGV["Email", i].Value.ToString();
    custCont.FAX = custKeyContactGV["FAX", i].Value.ToString();
}

custDC.CustomerContacts.InsertOnSubmit(custCont);
custDC.SubmitChanges();

感谢您的帮助。

0 个答案:

没有答案