在C#中使用Linq Lambda更新多个记录

时间:2015-12-07 11:40:49

标签: c# linq lambda

我有一个ThresholdTable表,其中有两列ID varchar(max)Value varchar(max)

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

我想将此更新为

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

我如何通过C#,Linq,Lambda表达来实现。

我这样做,

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();
}

请建议我一些更好的方法。

3 个答案:

答案 0 :(得分:0)

Linq用于查询数据,而不是用于更新数据。

现在,为了更好地替代您的代码,如果要更新许多值,您可以将所需的值放在Dictionary中,并在循环浏览时更新您的值,例如

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();

答案 1 :(得分:0)

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();
    }
}

希望这会有所帮助

答案 2 :(得分:0)

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.