Wednesday, October 19, 2016

NHibernate Issue: Unexpected updates are triggered

A colleague came to me with the following NHibernate problem; he loads some data from the database using the QueryOver syntax. Although he doesn’t do anything else with the data, NHibernate detects that the list is changed and tries to flush the changes to the database.

What’s causing NHibernate to think that an item has changed?

We figured out the reason after some investigation.

Inside our database we have nullable column e.g.:

Age [int] NULL  -- Nullable column

But inside the mapping we decided to map it to a not nullable property:

<property name="Age" />

public virtual int Age { get; set; }

The moment that the data is loaded and NHibernate sees a null value for Age, inside the property it will be set to 0(the default value for an int).

As the value has changed, NHibernate will detect this and tries to flush the change afterwards.

The solution is to make the property nullable:

public virtual int? Age { get; set; }

No comments: