简体   繁体   中英

Updating Multiple records using Linq Lambda in C#

I have a ThresholdTable table with two columns ID varchar(max) and Value varchar(max)

ID |  Value
----------------
1  |  0701224225
2  |  0701224012

I want to update this to

ID |  Value
----------------
1  |  105394
2  |  105595

How I can achieve through C#, Linq, Lambda expression.

I am doing this way,

private const string ThresholdValue1 = "1";

private const string ThresholdValue2 = "2";

var Setting = this.context.ThresholdTable.Where(p => p.ID.Equals(ThresholdValue1) || p.ID.Equals(ThresholdValue2));
foreach (var s in Setting)
{
    if (s.ID.Equals(ThresholdValue1))
    {
        s.Value = "105394";
    }
    else if (s.ID.Equals(ThresholdValue2))
    {
        s.Value = 105595;
    }
    this.context.SaveChanges();
}

Please suggest me some better way.

Linq is for querying data, not for updating them.

Now, for a better alternative of your code, if you many values to update, you can put your desired values in a Dictionary and update your values while looping through them like

var valuesToPopulate = new Dictionary<string, string> { 
    { "1", "105394" }, 
    { "2", "105595" } 
};

foreach (var threashold in this.context.ThresholdTable)
{
    var valueToPopulate = valuesToPopulate.FirstOrDefault(d => d.Key.Equals(threashold.ID.Equals));
    if (!valueToPopulate.Equals(new KeyValuePair<string, string>()))
        threashold.Value = valueToPopulate.Value;
}
this.context.SaveChanges();
public void updateMultiple()
{
    var ls = new int[] { 2, 3, 4 };
    var name = "xyz";
    using (var db = new SomeDatabaseContext())
    {
        var some = db.SomeTable.Where(x => ls.Contains(x.friendid)).ToList();
        some.ForEach(a =>
                        {
                            a.status = true;
                            a.name = name;
                        }
                    );
        db.SubmitChanges();
    }
}

Hope this will help

Try to abstract the concrete IDs and threshold values into a structure instead of handling them separately with if and || . You could use an array, a list or - since you have ID/value combinations - a dictionary:

var newThresholds = new Dictionary<string, string>
    { 
        { "1", "105394" }, 
        { "2", "105595" } 
    };

var thresholdsToUpdate = this.context
    .ThresholdTable
    .Where(t => newThresholds.Keys.Contains(t.ID));

foreach (var threshold in thresholdsToUpdate)
{
    threshold.Value = newThresholds[threshold.ID];
}

this.context.SaveChanges();

However, LINQ is a query interface - you can only use it to read data, not to update it. Hence, you can load the correct rows with a LINQ query, but have to update them outside the query in a regular foreach loop.

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