0

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();               
    }
}
4
  • 4
    The "attach" and "state" lines are not needed because the entity is already attach in this example. Commented Jul 6, 2016 at 22:59
  • unfortunately, it is not working Commented Jul 6, 2016 at 23:13
  • Are you able to run SQL Profiler to see if/what is hitting the database? Commented Jul 6, 2016 at 23:51
  • Sorry, it was my stupid mistake, I forgot to update entity model. Everything works with the code below. Commented Jul 7, 2016 at 0:00

2 Answers 2

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

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

Comments

1

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();               
        }
    }

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.