Update db record in foreach loop with Entity Framework in asp.net mvc 6

asp.net asp.net-mvc c# entity-framework entity-framework-6

Question

I know there are similar questions, but in my case something is wrong. Just trying to update each row, but it does nothing for some reason and no errors.

Thanks.

public ActionResult Index()
{
    using (var db = new DoskaUsContext())
    {
        foreach (var category in db.Categories)
        {
            category.Count = 25;
            db.Categories.Attach(category);
            db.Entry(category).State = EntityState.Modified;
        }

        db.SaveChanges();

        return View();               
    }
}
1
0
7/7/2016 4:37:44 AM

Accepted Answer

//3. Mark entity as modified
db.Entry(Category).State = System.Data.Entity.EntityState.Modified;     

//4. out side for loop call SaveChanges
db.SaveChanges();

It works.

1
7/6/2016 11:14:44 PM

Popular Answer

You can try the following, I haven´t tested it yet:

public ActionResult Index(Categories category)
    {

        using (var db = new DoskaUsContext())
        {
            foreach (var cat in category)
            {
                category.Count = 25;
                db.Entry(category).State = EntityState.Modified;
            }

            db.SaveChanges();
            return View();               
        }
    }


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow