2

I'm working on my 5th or so ASP.NET MVC webapp in the past few years, and I still haven't seen a good way to take the data submitted in an Edit/Update form and save it to the database efficiently when using an ORM like Linq to SQL or the Entity Framework.

Just to be clear, the problem is with the Create action you can take the object as a parameter:

public ActionResult Create(QuestionGroup newGroup)

With an Edit action, the object must be linked to the ORM and updated, rather than created from scratch like the ModelBinder will do.

I have always solved this problem one of two ways: either I will manually update each property on the object (one line of code per property) or I will write a method that uses reflection to find every property to update it and copies the value over.

I feel certain that, by now in version 3 of MVC, there is a blessed way to do this better, but I cannot find it! What's the secret to do this more simply and gracefully??

1
  • i know this is an old question, but how about Automapper ? it could save you the property copy ritual Commented Dec 25, 2011 at 15:16

2 Answers 2

2

Well this is embarrassing... there is a method Controller.UpdateModel with several overloads that will do the trick. I searched the internet hi and low, only to accidentally find the answer with IntelliSense right after posting the question.

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

Comments

2

I've discovered that you can also do the following with the Entity Framework. It has pros and cons vs the other option, but it should work just as well as the previous answer:

[HttpPost]
public ActionResult Edit(QuestionGroup updatedGroup)
{
    try
    {
        context.QuestionGroups.Attach(updatedGroup);
        context.ObjectStateManager.ChangeObjectState(updatedGroup, System.Data.EntityState.Modified);

        ValidateModel(updatedGroup);

        if (this.ModelState.IsValid)
        {
            context.SaveChanges();
            return RedirectToAction("Index");
        }
    }
    catch
    {
    }

    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.