I am trying to save / protect certain fields in a view model

I am trying to implement the solution found here , but as soon as I replace the Users class with the EditUserViewModel class (one that has fewer fields than the Users class), and as soon as I get to this line

db.Entry(users).State = EntityState.Modified;

in this code

    [HttpPost]
    public ActionResult Edit(EditUserViewModel users)
    {
        if (ModelState.IsValid)
        {
            db.Entry(users).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(users);
    }

I get an error

The entity type EditUserViewModel is not part of the model for the current context.

Now I assume that this error is due to the fact that my DBContext uses the Users class, and not the EditUserViewModel class. Am I missing a step or is there a way to fix this?

+1
source share
1 answer

You need to combine the data from your MV into the Model class.

if (ModelState.IsValid)
{
    var existingUser = db.Users.Single(p => /* query to find your user */);

    existingUser.From = user.From;
    existingUser.CC = user.CC;
    // etc.

    db.SaveChanges();

    return RedirectToAction("Index");
}
+1
source

All Articles