With ASP.net MVC I’m doing this:
[HttpPost]
[TransactionFilter]
public ActionResult Create(User user)
{
// Ommited some things for the sake of brevity
_userRepository.Add(user);
return RedirectToAction("Details", new { Id = user.Id });
}
This works as I expected. Now I’m trying to do this:
[HttpPost]
[TransactionFilter]
public ActionResult Create(User user, ChildOfUser userChild)
{
// Ommited some things for the sake of brevity
var parent = _userRepository.GetById(user.Id);
parent.Children.Add(userChild);
return RedirectToAction("Details", new { Id = userChild.Id });
}
This fails because userChild.Id is null. The first case works because in the repo I call session.Save(user);, and this call will change the user.Id property.
The (User)parent.Children.Add(userChild); call won’t change the userChild.Id property. Only after calling transaction.Commit(); the userChild.Id will have a meaningfull value. While I expect that the Id would be set by adding the userChild to the collection.
Now, should NHibernate handle this? Or are my expectations wrong? If there’s a way to let NHibernate handle this that would be awesome.
EDIT
The Id’s in this case are always GUID’s. Can I set them myself (they are Globally unique right…), and will NHibernate use that as if it generated the Id itself?
I’ve had this particular problem solved by using the ISession.Flush() method after using .Add()
I wouldn’t recommend this practise though. Nowadays I set the Guid Id immediately in the entities constructor. This makes both MVC and NHibernate happy.