Inserting data using Linq
I have a linq query to insert data in table. but its not working. I saw some example on internet tried to do like that but doesn't seems to work.
Tablename: login has 3 columns userid, username and password. I set userid as autoincrementing in database. So I have to insert only username and password everytime.Here's 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 w开发者_运维百科ork.
db.SubmitChanges();
have a look on 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 should attach to the particular object Context .But it wont reflect in database .If you want to insert any values try with InsertOnSubmit(object) and do SubmitChanges() to save it in database
Attach() is the wrong method, you need to call InsertOnSubmit() to let Linq-To-Sql generate an insert statement for you. Attach() is for distributed scenarios, where your entity has not been retrieved via the same data-context that is used for submitting 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();
Method to save employee details into Database.
Insert, Update & 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();
精彩评论