Updating only filled properties
Is there a way for NHibernate to only update fields that have no default? Let's say we have this simple class:
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
We also have a standard NHibernate mapping using properties for each field and Id for the Id field.
Let's say we want the page to just update the name, so we send the ID, store it in a hidden field, and show the text field for the name. User changes name and saves beats. We return a POST, a new Person object, and assign the incoming ID and name. Then we will tell NHibernate to update the database.
The problem is that Age is obviously falling back to 0 in the database as it hasn't been populated by the return from POST. The most obvious way is to send the Age value to the page, store it in a hidden field, and revert it back before saving. This works great until you get a few more properties on your object and only want to change their full copy on screen (or a large list of Person objects that might require storing a lot of values in hidden fields).
So back to the subject of the question, is there a way to tell NHibernate to basically ignore the Age property as it will default to (0) before updating, or am I stuck with a metric ton of hidden values to keep existing values?
a source to share
This sounds a little suspicious. Typically when you go to edit a Hibernate object, you first load it from the database, make changes to it, and then save it back to the database. Usually you shouldn't create a new object, set its ID and any arbitrary properties, and then save the new object, because as you say, any properties that are not set are likely to be set to their default values.
By loading it from the database, all properties are populated appropriately, so you don't have to worry about saving their state. The Hibernate session is responsible for maintaining the state of these objects until you save and dump them to the database.
There are various strategies for dealing with a hibernate session through web requests. Check out this article: http://hibernatebp.blogspot.com/ - look at session management strategies. "Session per request with separate objects" might be good in your case.
a source to share