Updating just one column value using LINQ

Suppose I have a column ID in a table and I want to increase one of its column values ​​by 1. How do I do this.

This is what I already have. The table has 3 properties, (id, category, value)

var col1= db.columns.Where(w => w.category.Equals("Cars"));

      

I want to increase the value in a table that has the category "Cars" by 1. What is a LINQ query for this.

A similar question may have been asked before, but the answer I haven't seen seems to be satisfactory enough.

+3


source to share


4 answers


var col1= db.columns.Where(w => w.category.Equals("Cars"));
foreach (var item in col1)
{
    item.SPECIFIC_PROPERTY = "VALUE";
}

try
{
    db.SubmitChanges();
}
catch (Exception ex)
{
   //Handle ex
}

      



+4


source


You can use an extension method .ForEach

(you will need to enumerate first), but Linq should be used to query, not update values.

So use foreach



foreach (var car in col1) {
  car.value +=1;
}

//some method to save changes

      

+3


source


You can just

  • create your query that will return what you want from db using where clause
  • Makes your changes to your code
  • Submit your changes

Here is an example on MSDN on how to update a row in DB link

+1


source


this way works for me:

 var cols = dbContext.table_name.Where(w => w.columnName == parameterName);
            foreach(var item in cols)
            {
                item.last_updated_date = dtNow;
            }

      

+1


source







All Articles