简体   繁体   English

如何通过LINQ to SQL更新和删除数据库中的记录?

[英]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? 我该怎么做?

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. 当您使用DataContext生成LINQ to SQL查询时,它将跟踪从该上下文中退出的查询中选择的对象。

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. 话虽这么说,如果您对返回的对象进行更改,然后在DataContext实例上调用SubmitChanges方法 ,则更改将被持久化回到基础数据存储中。

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). 如果要删除对象,则将对象传递给Table<T>实例上DeleteOnSubmit方法 (其中T是数据库中表的模型的类型)。 Then, when you call SubmitChanges on the DataContext, the records represented by the models passed to the DeleteOnSubmit method will be deleted. 然后,当您在DataContext上调用SubmitChanges时,将删除传递给DeleteOnSubmit方法的模型所表示的记录。

var context = new MyDataContext(); var context = new MyDataContext(); var newObj = new User(); var newObj = new User(); newObj.UserID = 1; newObj.UserID = 1; newObj.Name = "Ted"; 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM