tags:

views:

347

answers:

4

I have a table "Users".. it has a column "ShowData"

using linq-sql how can I loop through every user and set ShowData to false for each user..

thanks

+2  A: 

If this column is in a SQL Server table, just issue this SQL statement:

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.

Anton Gogolev
IIRC, Linq-2-Sql uses IQueryable so no data would be loaded unless it was specifically requested, that said, adding a SPROC would likely be a good idea, to make sure that optimal SQL was sent down the wire.
Nate Bross
+5  A: 

Create a linq to sql classes designer file. Then drop the Users table on to the designer surface.

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:

using (TheDataContext dc = new TheDataContext())
{
  dc.ExecuteCommand("UPDATE Users SET ShowData = 0");
}
David B
+2  A: 

Create a stored procedure

CREATE PROCEDURE HideData 
AS
update Users set ShowData = 0

Using your server explorer dropdown this procedure in your Dbml

And in your function:

using (CustomDataContext context= new CustomDataContext())
{
  context.HideData();
}
Gregoire
A: 

This example demonstrates how to do everything using 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;
);
Michael