Update records using LINQ

后端 未结 8 1583
迷失自我
迷失自我 2020-12-04 17:24

I need to set a value in a table for a subset of rows. In SQL, I would do this:

UPDATE dbo.Person SET is_default = 0 WHERE person_id = 5

Is

8条回答
  •  死守一世寂寞
    2020-12-04 17:57

    Yes. You can use foreach to update the records in linq.There is no performance degrade.

    you can verify that the standard Where operator is implemented using the yield construct introduced in C# 2.0.

    The use of yield has an interesting benefit which is that the query is not actually evaluated until it is iterated over, either with a foreach statement or by manually using the underlying GetEnumerator and MoveNext methods

    For instance,

    var query = db.Customers.Where (c => c.Name.StartsWith ("A"));
    query = query.Where (c => c.Purchases.Count() >= 2);
    var result = query.Select (c => c.Name);
    
    foreach (string name in result)   // Only now is the query executed!
       Console.WriteLine (name);
    

    Exceptional operators are: First, ElementAt, Sum, Average, All, Any, ToArray and ToList force immediate query evaluation.

    So no need to scare to use foreach for update the linq result.

    In your case code sample given below will be useful to update many properties,

     var persons = (from p in Context.person_account_portfolio where p.person_name == personName select p);
    
    //TO update using foreach
    
    foreach(var person in persons)
    {
    //update property values
    }  
    

    I hope it helps...

提交回复
热议问题