[英]linq to sql - loop through table data and set value
I have a table "Users".. it has a column "ShowData" 我有一个表“用户”..它有一个列“ShowData”
using linq-sql how can I loop through every user and set ShowData to false for each user.. 使用linq-sql我如何遍历每个用户并为每个用户将ShowData设置为false。
thanks 谢谢
Create a linq to sql classes designer file. 创建一个linq to sql类设计器文件。 Then drop the Users table on to the designer surface.
然后将Users表放到设计器表面上。
using (TheDataContext dc = new TheDataContext)
{
//pull all users into memory, not recommended for large tables.
List<User> users = dc.Users.ToList();
foreach(User theUser in users)
{
theUser.ShowData = false;
}
//send all these property changes back to the database.
dc.SubmitChanges();
}
And to guard myself against downvoting: 并防止自己反对downvoting:
using (TheDataContext dc = new TheDataContext())
{
dc.ExecuteCommand("UPDATE Users SET ShowData = 0");
}
Create a stored procedure 创建存储过程
CREATE PROCEDURE HideData
AS
update Users set ShowData = 0
Using your server explorer dropdown this procedure in your Dbml 在Dbml中使用服务器资源管理器下拉列表中的此过程
And in your function: 在你的功能:
using (CustomDataContext context= new CustomDataContext())
{
context.HideData();
}
This example demonstrates how to do everything using Linq. 此示例演示如何使用Linq完成所有操作。
using (MyDataContext dataContext = new MyDataContext(connectionString))
{
dataContext.Users.ToList().ForEach(user => user.ShowData = false);
// commit changes made to entities (generates UPDATE statements for you)
dataContext.SubmitChanges();
}
What's happening is: 发生的事情是:
// IQueryable<User> (query setup)
dataContext.Users
// from IEnumerable<User> to List<User> (pull from Sql Server into memory)
.ToList()
// via enumerating list of User entities (now in memory)
.ForEach
(
// define entity in this iteration
user =>
// define operation on entity
user.ShowData = false;
);
If this column is in a SQL Server table, just issue this SQL statement: 如果此列位于SQL Server表中,则只发出以下SQL语句:
update Users set ShowData = 0 // where ...
Don't even think about loading all users into memory, setting a single property and then saving them to the database. 甚至不要考虑将所有用户加载到内存中,设置单个属性然后将它们保存到数据库。
If this is an in-memory table, you don't actually need LINQ to SQL here at all. 如果这是一个内存表,那么你根本不需要LINQ to SQL。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.