Use linq to generate direct update without select

前端 未结 7 912
感情败类
感情败类 2020-11-29 05:34

G\'day everyone.

I\'m still learning LINQ so forgive me if this is naive. When you\'re dealing with SQL directly, you can generate update commands with conditionals

7条回答
  •  甜味超标
    2020-11-29 06:32

    No, neither LINQ nor LINQ to SQL has set-based update capabilities.

    In LINQ to SQL, you must query for the object you wish to update, update the fields/properties as necessary, then call SubmitChanges(). For example:

    var qry = from product in dc.Products where Product.Name=='Foobar' select product;
    var item = qry.Single();
    item.Count = 0;
    dc.SubmitChanges();
    

    If you wish to do batching:

    var qry = from product in dc.Products where Product.Type==1 select product;
    foreach(var item in qry)
    {
      item.Count = 0;
    }
    dc.SubmitChanges();
    

    Alternatively, you could write the query yourself:

    dc.ExecuteCommand("update Product set Count=0 where Type=1", null);
    

提交回复
热议问题