Insert data using Linq

I have a linq query to insert data into a table. but it does not work. I saw an example on the Internet trying to do so, but it doesn't seem to work.

Tablename: login has 3 user columns, username and password. I set userid as auto increment in the database. So I need to insert only username and password each time. Here is my code.

linq_testDataContext db = new linq_testDataContext(); login insert = new login(); insert.username = userNameString; insert.Password = pwdString; db.logins.Attach(insert);// tried to use Add but my intellisence is not showing me Add.I saw attach but dosent seems to work. db.SubmitChanges(); 
+4
source share
3 answers

look at http://www.codeproject.com/KB/linq/LINQToSQLBaseCRUDClass.aspx

  linq_testDataContext db = new linq_testDataContext(); login insert = new login(); insert.username = userNameString; insert.Password = pwdString; db.logins. InsertOnSubmit(insert); db.SubmitChanges(); 

If you attach, it must attach to a specific Context object. But it will not reflect in the database. If you want to insert any values, try InsertOnSubmit (object) and do SubmitChanges () to save it to the database

+5
source

Attach () is the wrong method, you need to call InsertOnSubmit () so that Linq-To-Sql generates an insert statement for you. Attach () is for distributed scripts where your object has not been retrieved through the same data context that is used to send the changes.

 linq_testDataContext db = new linq_testDataContext(); login insert = new login(); insert.username = userNameString; insert.Password = pwdString; db.logins.InsertOnSubmit(insert);// tried to use Add but my intellisence is not showing me Add.I saw attach but dosent seems to work. db.SubmitChanges(); 
+3
source

A way to store employee information in a database.

Insert, update and delete in LINQ C #

  Employee objEmp = new Employee(); // fields to be insert objEmp.EmployeeName = "John"; objEmp.EmployeeAge = 21; objEmp.EmployeeDesc = "Designer"; objEmp.EmployeeAddress = "Northampton"; objDataContext.Employees.InsertOnSubmit(objEmp); // executes the commands to implement the changes to the database objDataContext.SubmitChanges(); 
+3
source

Source: https://habr.com/ru/post/1308048/


All Articles