Search code examples
c#asp.netlinqlinq-to-sql

updating multiple records in database with linq to sql without loop, is it possible?


ok, let say i want to update multiple rows in database at once, without looping, if we do it with loop, it might look like this :

var products = (from prod in context.Products
               where prod.ProductCategoryID == myProductID
               select prod).ToList();


// modify each object
foreach (var product in products)
{
    product.PhoneNumber = ???;
    product.Name = ???;
    product.Address = ???;
}


context.SubmitChanges();

is there better way to do this? without doing any loop? consider me as a beginner on linq, so if there is some better way, it would be great if you provide me some example, thanks in advance.


Solution

  • LINQ is for quering records. Your current foreach loop is more readable and if you try other approach then it will use loop internally.

    You can see this answer which modifies the collection using LINQ, but it is not the recommended way.