简体   繁体   中英

LINQ to SQL update all records

I have a table like this:

在此处输入图片说明

I want to update Seasonal_Voucher column for all users with something

like : UPDATE Users SET Seasonal_Voucher = 'Something'

I tried this but it wont work:

using (DataClassesDataContext context = new DataClassesDataContext())
{
    Users use = context.Users;
    {
        use.Seasonal_Voucher =DropDownList1.SelectedItem.ToString();
    };
    context.Refresh(0);
    context.SubmitChanges();
}

As Sami suggested in the comments, "it won't work" is too broad. However, here is a basic modification of your code: (since you tagged linq also, I assume you are familiar with lambda syntax)

using (DataClassesDataContext context = new DataClassesDataContext())
{
    foreach (var use in context.Users)
    {
        use.Seasonal_Voucher = DropDownList1.SelectedItem.ToString();
    };
    //context.Refresh(0);
    //context.SubmitChanges();
    context.SaveChanges();
}

I realize (as Rob mentions) that loading the entire table into memory for updating is not wise. As such, you could simply try the ExecuteSqlCommand method (since it looks like you're using Entity Framework anyways). MSDN: Database.ExecuteSqlCommand Method

It is useful for bulk updates.

string sqlQuery = "UPDATE Users SET Seasonal_Voucher = '" + DropDownList1.SelectedItem.ToString() + "'";
using (DataClassesDataContext context = new DataClassesDataContext())
{
    context.Database.ExecuteSqlCommand(sqlQuery);
}

Alternatively with reference to how to update the multiple rows at a time using linq to sql? Below code does the same. However as its mentioned by Keyur, entire table will be loaded for the update operation which would be a performance bottleneck.

using (DataClassesDataContext context = new DataClassesDataContext())
{
   var users= context.Users.ToList();
    users.ForEach(user=>user.Seasonal_Voucher=DropDownList1.SelectedItem.ToString());
   context.SaveChanges();

}

or

using (DataClassesDataContext context = new DataClassesDataContext())
{
   context.Users.ToList().ForEach(user=>user.Seasonal_Voucher=DropDownList1.SelectedItem.ToString());
   context.SaveChanges();   
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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