masoud ramezani
masoud ramezani

Reputation: 22930

How can I Update and delete records in my database by LINQ to SQL?

Is there the ability for doing this work? How can I do this work?

Upvotes: 0

Views: 160

Answers (2)

Brian Mains
Brian Mains

Reputation: 50728

var context = new MyDataContext(); var newObj = new User(); newObj.UserID = 1; newObj.Name = "Ted";

context.Users.InsertOnSubmit(newObj);  //queues for submission
context.SubmitChanges(); //submits to backend

or for update:

var context = new MyDataContext();
var user = context.Users.First(i => i.UserID = 1);
//entities self aware and automatically synced to database when a value changes
user.Name = "Dave";

context.SubmitChanges(); //knows about updated record

Upvotes: 3

casperOne
casperOne

Reputation: 74540

When you use a DataContext to generate a LINQ to SQL query, it will track objects that are selected from queries that eminate from that context.

That being said, if you make changes to the objects returned and then call the SubmitChanges method on the DataContext instance, the changes will be persisted back to the underlying data store.

If you want to delete an object, then you pass the object to the DeleteOnSubmit method on the Table<T> instance (where T is the type that is the model for the table in the database). Then, when you call SubmitChanges on the DataContext, the records represented by the models passed to the DeleteOnSubmit method will be deleted.

Upvotes: 3

Related Questions