R – Only updating filled in properties

netnhibernate

Is there a way to have NHibernate only update the fields that don't have the default value filled in? 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.

Say we want a page to just update the Name, so we send down the Id, store it in a hidden field, and show a text box for the name. The user modifies the name and hits save. We POST back, new up a Person object, and assign the incoming Id and Name. We then tell NHibernate to update the database.

Problem is, the Age obviously gets set back to 0 in the database as it wasn't filled in coming back from the POST. The most obvious way around this is to send the Age value to the page, store it in a hidden field, and fill it back in before saving. That works fine until you get quite a few more properties on your object and only want to modify a hand full of them on the screen (or a large list of Person objects, which might require storing lots 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 since it'd have a default value (0) before being updated, or am I stuck with a metric ton of hidden fields to keep the existing values?

Best Answer

In the post back, Retrieve the persisted entity from the repository with the Id and update just the Name and persist it. This way, you don't need to maintain the values in hidden field.