-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.

  • Does this answer your question ? https://stackoverflow.com/questions/21592596/update-multiple-rows-in-entity-framework-from-a-list-of-ids – Shahriyar Mar 19 '21 at 17:22
  • Simple answer: not supported. – Gert Arnold Mar 19 '21 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();` – Taha Ahmed Mar 20 '21 at 08:34

1 Answers1

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);
Serge
  • 40,935
  • 4
  • 18
  • 45
  • "i do not want to use foreach loop". They're looking for bulk update. Also, neither alternative is necessary. – Gert Arnold Mar 19 '21 at 21:08
  • 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. – Serge Mar 19 '21 at 21:12
  • 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"). – Gert Arnold Mar 19 '21 at 21:25
  • 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();` – Taha Ahmed Mar 20 '21 at 15:06
  • 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. – Serge Mar 20 '21 at 15:58