Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating just one column value using LINQ

Suppose I have the ID of a column in a table and I want to increment one of it's column values by 1. How should I go about this.

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

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

I want to increment the value in the table which has category "Cars" by 1. What is the LINQ Query for this.

A similar question may have been asked before but no answer I have seen seems satisfactory enough.

like image 644
Timmay Avatar asked Jan 08 '23 23:01

Timmay


2 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
}
like image 87
Ahmed Elazazy Avatar answered Jan 10 '23 12:01

Ahmed Elazazy


You could use a .ForEach extension method (you would have to enumerate first), but Linq should be used to query, not to update values.

So use a foreach

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

//some method to save changes
like image 34
Raphaël Althaus Avatar answered Jan 10 '23 11:01

Raphaël Althaus