2

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.

3
  • Parallel.For may be what your looking for - msdn.microsoft.com/en-us/library/… and msdn.microsoft.com/en-us/library/dd460713.aspx Commented May 21, 2013 at 7:04
  • Habib provides the answer. The only improvement I see is removing the ToList but that is off topic. Commented May 22, 2013 at 19:19
  • is n't everyone free to give their opinion? to help other have a better understanding, i wonder. Commented May 23, 2013 at 5:44

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

In what i have heard about, i guess EF or Linq to SQL does not support bulk operations. Please suggest.
@saravanan, that is right. For example in LINQ to SQL we have InsertAllOnSubmit but internally it uses a loop.
Thank you very much for sharing this info. I have learnt this now.
hello @habib, thx for your response, well what i get from your explaination is most likely linq will always do loop?
@HendraLim, yes LINQ internally uses loop for most of the queries.
0

You can use that line:

var products = (from prod in context.Products
                where prod.ProductCategoryID == myProductID
                select new Product(prod.PhoneNumber.ToLower(), prod.Name.ToUpper(), prod.Address.Trim()).ToList();

If you wanna change your products directly in your context object : make a specific function in Products class only. It will simply well designed.

 (from prod in context.Products
  where prod.ProductCategoryID == myProductID
  select prod.MakeChange(myPhoneNumber, myName, myAddress);

As you can call that line of code, prod should be changed along the LINQ query.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.