开发者

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

Is there the ability for开发者_StackOverflow社区 doing this work? How can I do this work?


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜