Heres the scenario: I have a User object like this:
public class User : BaseEntity<User>, IAggregateRoot
{
public virtual string Name { get; set; }
public virtual string Username { get; set; }
public virtual string Password { get; set; }
public virtual string SecretQuestion { get; set; }
public virtual string SecretAnswer { get; set; }
public virtual DateTime LastLogin { get; set; }
}
During the editing of this object, i load it into the view, but i only want to update some of the properties (ie i wouldnt want to update LastLogin property). In this situation what would i do?
Is the best strategy to create a user viewmodel, and will nhibernate cope with this when i try to update a user object with a null LastLogin field?
Thanks in advance.
EDIT
Something like this:
public class UserViewModel
{
public string Name {get;set;}
public string UserName {get;set;}
public string Password {get;set;}
public string SecretQuestion {get;set;}
public string SecretAnswer {get;set;}
}
And then the editing:
public ActionResult Edit(int id)
{
return View(_userRepository.FindById(id));
}
[HttpPost]
public ActionResult Edit(int id, UserViewModel userViewModel)
{
try
{
//Not sure how to update the model
//with the view Model and save.
_userRepository.Update(????);
return RedirectToAction("Index");
}
catch
{
return View();
}
}
A good approach is to create a
UserViewModelwith only the properties you want to display/update. Don’t let nHibernate know about the view model. Then, when the edits are posted back to your controller you retrieve the actual User object from nHibernate, update it’s properties from the view model, and then save it back to the database.Update
Something like this:
In a project I’ve been working on recently I created a ViewModelBase class which includes methods that maps properties from a domain model to a view model and back again based on matching the property name and type. All my view models are derived from ViewModelBase.
There are other tools like AutoMapper that do this sort of thing and much, much more.