I'm having a hard time using NHibernate with MVC 5. The problem is that NHibernate needs the Id property of my class to be private or protected, but then the MVC model binder can't set the Id on an existing entity, so NHibernate views it as a new record, and inserts it instead of editing it.
public interface IEntity
{
int Id {get; }
}
public class User : IEntity
{
public virtual int Id {get; protected set;}
public virtual string Email {get; set;}
public virtual DateTime? LastLogin {get; set;}
}
This works just fine
public JsonResult SaveUser(User user)
{
var userModel = new UserModel();
if(userModel.SaveUser(user)) return Json(new {success = true});
return Json(new {success = false});
}
This fails, because Id has a protected set, which is necessary for an NHibernate entity. So, since the MVC model binder can't set Id, NHibernate views it as a new entity.
public JsonResult EditUser(User user)
{
var userModel = new UserModel();
userModel.EditUser(user);
}
So it looks like I need to basically duplicate my entity classes as view models, but this seems really tedious (not to mention anti-DRY). The only difference between the two classes would be the view model class would have a publicly settable Id. I can make this a little less tedius by using AutoMapper, but it still looks like I'd need to duplicate my classes as view models. It does have a feature to map from dynamic, but that still wouldn't allow me to properly set the Id for an existing entity.
So, am I missing something here? Is there a way I can do this without having to make two almost identical classes?