imaginationpluscode
imaginationpluscode

Reputation: 137

Entity Framework LINQ insert command failing. MVC3

Hi I'm trying to do a basic update based on an id using Linq and the entity framework. I'm very new to this but I do not see the problem.

My entity class object is declared at the controller level.

gwwbnEntities db = new gwwbnEntities();

The Method grabs a querystring id and updates the user's registration status who is represented by that id.

public ActionResult ConfirmedAccount(int id)
    {

        var q = from u in db.user_registration
                where u.id == id && u.reg_status == null
                select u;

        if (q.Any())
        {
            foreach(var item in q){

            user_registration user = item;
            user.reg_status = 202;
            db.Entry(user).State = EntityState.Modified;
            db.SaveChanges();
            }

            return View();
        }
        else
        {
            return RedirectToAction("RegistrationError");
        }
    }

Any help would be greatly appreciated! Again everything works and populates correctly, but the context object.SaveChanges() method fails everytime.

Thanks guys!

Upvotes: 0

Views: 553

Answers (1)

Pawel
Pawel

Reputation: 31610

The exception you are seeing is because you have an open data reader (foreach) and you are trying to create transaction (EF does it for you) in SaveChanges(). Call SaveChanges outside the loop. In addtion: Don't set the state to Modified - EF will detect that properties changed and will automatically set the state accordingly. You may want to do .ToList() on the q before doing anything. At the moment you are sending to queries to the database (one for .Any() and one to get entities). If you do .ToList() you will send only one query that brings entities but .Any() would be called on the list not on the database so it will be much faster and there is no trip to the database. Also ToList() force query evaluation so your foreach loop will not keep the data reader open as it will iterate on the list.

Upvotes: 3

Related Questions