我试图通过linq将数据插入到sql概念中。我写下这样的代码。这里客户是我想要插入数据的表名。怎么实现呢? 以下代码无效。如何通过这个概念插入数据。
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Dim context As New linq_to_sql_classesDataContext
Dim custid As New Customer
custid.CustomerID = Trim(txt_custid.Text)
custid.CompanyName = Trim(txt_companyname.Text)
custid.ContactName = Trim(txt_contactname.Text)
custid.ContactTitle = Trim(txt_contacttitle.Text)
custid.Address = Trim(txt_address.Text)
custid.City = Trim(txt_city.Text)
custid.Region = Trim(txt_region.Text)
custid.PostalCode = Trim(txt_postalcode.Text)
custid.Country = Trim(txt_country.Text)
custid.Phone = Trim(txt_phone.Text)
custid.Fax = Trim(txt_fax.Text)
context.Customers.Attach(custid)
context.SubmitChanges()
End Sub
谢谢
答案 0 :(得分:3)
您应该使用InsertOnSubmit
方法:
context.Customers.InsertOnSubmit(custid)
context.SubmitChanges()
答案 1 :(得分:0)
你应该使用
context.Customers.Add(custid)
答案 2 :(得分:0)
检查此链接以了解LINQ to SQL插入:
private void SaveCustomerInfo()
{
using (NorthwindDataContext context = new NorthwindDataContext())
{
//Create a new instance of the Customer object
Customer cust = new Customer();
//Add new values to each fields
cust.CustomerID = TextBoxID.Text;
cust.CompanyName = TextBoxCompanyName.Text;
cust.ContactName = TextBoxContactName.Text;
cust.ContactTitle = TextBoxContactTitle.Text;
cust.Address = TextBoxAddress.Text;
cust.City = TextBoxCity.Text;
cust.Region = TextBoxRegion.Text;
cust.PostalCode = TextBoxPostalCode.Text;
cust.Country = TextBoxCountry.Text;
//Insert the new Customer object
context.Customers.InsertOnSubmit(cust);
//Sumbit changes to the database
context.SubmitChanges();
//Display Message for successful operation
LiteralMessage.Text = "<p style='color:Green;'>Information Successfully saved!</p>";
}
}