-1

I want to update all the records of a particular column in MVC5 using linq query

var PriceRecord = db.tblPurchasePrices.Where(z => z.ID == id).SingleOrDefault();
var PurchasePriceList = db.tblPurchasePrices.Where(z => z.SizeID == PriceRecord.SizeID && z.ProductID == PriceRecord.ProductID && z.CategoryID == PriceRecord.CategoryID).ToList();

        foreach (var item in PurchasePriceList)
        {
            item.IsActive = false;
            db.SaveChanges();
        }

i do not want to use foreach loop to update record one by one and save changes. i want all values in a particular column to update in one go.

3
  • Does this answer your question ? stackoverflow.com/questions/21592596/… Commented Mar 19, 2021 at 17:22
  • Simple answer: not supported. Commented Mar 19, 2021 at 21:05
  • i dont not want to use foreach loop, want to update all records using linq query like db.tblPurchasePrices.Where(z => z.ID == id).ToList().value(v=> v.isActive = false); db.SaveChanges(); Commented Mar 20, 2021 at 8:34

1 Answer 1

0

Try this code, you can save all changes in one trip to DB:

 foreach (var item in PurchasePriceList)
        {
            item.IsActive = false;
          db.Entry(item).State = EntityState.Modified;
         }
 db.SaveChanges();

or another syntax:

foreach (var item in PurchasePriceList)
        {
            item.IsActive = false;
          db.Entry(item).Property(i=> i.IsActive).IsModified = true;
         }
 db.SaveChanges();

Another way to update bulk data that maybe faster (maybe not) is to create a stored procedure with PriceRecord parameters and execute like this :

db.Database.ExecuteSqlCommand("stored_procedure_name @params", params);
Sign up to request clarification or add additional context in comments.

5 Comments

"i do not want to use foreach loop". They're looking for bulk update. Also, neither alternative is necessary.
I am sorry, but I am not saving records one by one as PO. I modified the needed records at first , after this in one trip saved all changes. This I call bulk modifying. I can' t imagine how it canbe done another way.
OK, that's a difference, but the other added statements are redundant or even worse. I still think they want bulk update ("i want all values in a particular column to update in one go").
i dont not want to use foreach loop, want to update all records using linq query like db.tblPurchasePrices.Where(z => z.ID == id).ToList().value(v=> v.isActive = false); db.SaveChanges();
How do you think linq works? Do you think they have special select operators? Linq converts all the operators to ForEach or to For . Linq it is just the way to write the shorter code.

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.