Say I have class called User, that is my basic entity (I use it with DbContext as DbSet Users), that I use as ground level for my Data-Access-Layers. Let's say 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 pure view where I only show whether user is Active or not, and simple checkbox that allows me to change that value. I don't want to load any other entity properties, specially property Photo as it's just insane. I've created ActivateUserModel that goes like this:
public class ActivateUserModel
{
[Key]
public int Id { get; set; }
public bool Active { get; set; }
}
I have strongly-typed view called Activate, that takes ActivateUserModel and displays it (it's only a checkbox and hidden for Id) and then I have [HttpPost] Activate action that captures ActivateUserModel, converts it to User entity, and then saves changes to database. This is POST action:
[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);
}
This works like a charm. I've monitored my queries issued against SQL server, and all I load is pair Id/Active and all I update is also Active change based on id.
However I don't like the code how it looks. Say I have entity that has 50 properties, and view that has 25. I don't want to write 25 lines where I say IsModified=true.
So my question is: is there more efficient way to do the same, without digging into any reflection-based methods? I want to transfer data from any view model to entity and then save only those properties.
Thank you in advance for responses, I hope I made question clear enough :)