MartinDotNet
MartinDotNet

Reputation: 2505

NHibernate save only part of an object

Application components: NHibernate 3.3 FluentNHibernate 1.3 I'm using Automapping only at the moment (maybe that's the problem).

I'm new to NHibernate so this may be a simple question.

Here's the basic structure (not actual classes).

class Family
{
   public virtual Guid ID { get; set; }
   public virtual IList<Person> Members { get; set; }
}
class Person
{
   public virtual Guid ID { get; set; }
   public virtual Family Family { get; set; }
   public virtual string Name { get; set; }
}

I have an "Edit" view for the person, that takes the ID as a parameter. The Action then loads the Person object by ID and renders the view.

The issue is when I then change something and post it back, the Person object's Family member is null, and therefore when it's save, the Person no longer has a family :(

I tried adding a "FamilyID" property, and then having that as a hidden property in the view, but there is then a problem with the NHibernate persisting it (I can post the error if that is the way this is supposed to work).

I could load the Person object when it's posted back, then just copy over some of the information but that seems wrong to me...

Any help would be greatly appreciated.

Upvotes: 0

Views: 565

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

I could load the Person object when it's posted back, then just copy over some of the information but that seems wrong to me...

If you do not have corresponding input fields for the Family properties inside your view those values will never be sent back to your controller. So you should retrieve them using the FamilyID (which you would have sent with a hidden field) from the database before updating your Person object. That's the correct flow.


UPDATE:

This being said the best way to handle this scenario is to use view models (DUH). So you will design a view model which will contain only the properties that are supposed to be edited by the user in the view. Then you will make your view strongly typed to the view model and your HttpPost controller action will take the view model as argument. Inside this action you will load the entire Person domain that needs to be updated from the database, set the properties that were modified from the view model (trivially easy with a tool such as AutoMapper) and then persist back your domain model to the database. Only the properties that were part of the view will be modified from this Person domain model.

Upvotes: 2

Related Questions