Updating multiple records in a database using linq to sql without a loop, is this possible?

ok, let's say I want to update several rows in the database at once, without a loop, if we do this with a 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 a better way to do this? without any cycles? consider me new to linq, so if there is a better way, it would be great if you would give me some example, thanks in advance.

+2
source share
2 answers

LINQ is for entering records. Your current foreach more readable, and if you try a different approach, it will use the loop inside.

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

+2
source

You can use this 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 want to change your products directly in your context, do the following: make a specific function only in the product class. It will just be well designed.

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

As you can call this line of code, prod should be changed at LINQ.

0
source

Source: https://habr.com/ru/post/1237471/


All Articles