Entity and Derived Presentation Model - Update Only Common Properties

Let's say I have a class called User, that is, my main object (I use it with DbContext as DbSet users), which I use as the main level for my Data-Access-Layers. Let's say the class looks like this:

public class User
{
    [Key]
    public int Id { get; set; }
    public bool Active { get; set; }
    public string Description { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    public byte[] Photo { get; set; }
    public DateTime Created { get; set; }
}

Now I want to have a clean view, where I only show if the user is active or not, and a simple checkbox that allows me to change this value. I do not want to load any other properties of the object, especially the Photo property, as this is just crazy. I created ActivateUserModel, which looks like this:

public class ActivateUserModel
{
    [Key]
    public int Id { get; set; }
    public bool Active { get; set; }
}

Activate, ActivateUserModel ( Id), [HttpPost] , ActivateUserModel, . POST:

    [HttpPost]
    public ActionResult Activate(ActivateUserModel model)
    {
        if (ModelState.IsValid)
        {
            User user = new User { Id = model.Id, Active = model.Active };
            db.Users.Attach(user);
            db.Entry(user).Property(u => u.Active).IsModified = true;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(model);
    }

. , SQL, , , Id/Active, , , id.

, . , , 50 , , 25. 25 , IsModified = true.

, : , - , ? .

, , :)

+3
1

:

[HttpPost]
public ActionResult Activate(ActivateUserModel model)
{
    if (ModelState.IsValid)
    {
        User user = db.Users.Single(u => u.Id == model.Id);
        db.Entry(user).CurrentValues.SetValues(model);
        db.SaveChanges();

        return RedirectToAction("Index");
    }
    return View(model);
}

db.Entry(user).CurrentValues.SetValues(model) , user model, , model user. , user .

, . .

Edit

user, Photo. , , IsModified. Entity Framework , , . , Modified .

, , . Photo UserPhoto, Id Photo, UserPhoto user. , , user .

" " user UserPhoto, UserPhoto . Photo user user UserPhoto .

2

, " ". :

, . model user, SetValues(model), EF Modified, . UPDATE . , UPDATE .

, , , . - UPDATE , . IsModified 25 , ViewModel, true. SLQ UPDATE 25 . , UPDATE - - .

+6

All Articles