Here is my scenario:
I'm using nhibernate, openning and closing the session in an IHttpModule (PreRequestHandlerExecute and PostRequestHandlerExecute).
Ninject takes care of injecting my session in all my repositories and I'm very happy with it.
Now suppose an Update to one of my entities (code simplified):
Controller:
User user = _userService.GetUser(id);
user.Name = "foo";
user.Email = "[email protected]";
user.Group = _groupService.GetGroup(idGroup);
if(_userService.Edit(user)) {
RedirectToAction("Index");
}
else {
return View(user);
}
Service:
if(ValidateUser(user) {
return _rep.Update(user);
}
return false;
ValidateUser is doing the validation logic and inserting any error in a IValidationDictionary that is a wrapper for the ModelState in the controller.
So far so good, I get all errors (if any) and I can show them in the view.
Here comes the problem:
When I try to save an user with an error (no name for instance), the method _rep.Update(user) is never called, but the user gets saved anyway.
Googling around it come to my knowledge the nhibernate AutoDirtyCheck, witch means that if I change an entity in memory, it will be persisted automatically in the database.
Very powerful feature I agree, but since my session is commited in PostRequestHandlerExecute, my invalid entity is saved anyway, something that I don't want.
I tried to remove this behavior using unhaddins, it worked, but then my child objects are not automatically saved when I save only the parent :(
So how to solve that?
Make ValidadeUser public and validade a copy before calling the _userService.GetUser(id)?
Put the validation logic elsewhere? Maybe in the entity class itself? (I like it so much separated!).
Thanks a lot in advance.