R – Why does NHibernate pass default values to an insert if Save is called before the object is populated

nhibernate

If I call Save on a new object, then populate its properties, NHibernate generates and insert statement that contains only the default values for the properties. For example (session is an open ISession):

var homer = new Person();
session.Save(homer);
homer.Name = "Homer J. Simpson";
session.Flush();

I thought that calling Save would make homer persistent and that NH would track any changes and include them in the insert. Instead, it issues an insert with the name property parameter set to null. If I put the Save call after the assignment then it works. This object has a GUID id assigned by NH so it's not doing a premature insert to get an identity.

ETA I'm using session-per-request in an ASP.NET app and the pattern I want to follow is:

MyObject myObject;
if (id == null)
{
    myObject = new MyObject();
    repository.Add(myObject);
}
else
{
    myObject = repository.GetMyObject(id);
}
// populate myObject's properties
// NH magic happens here when the HTTP request ends

Best Answer

I think your assumption in this case is simply incorrect.

Reading the code sample you provided, you could just as well expect NHibernate to insert the object, and then subsequently change the Name and then issue an Update. That, however, would assume that Flush implicitly saves the changed state.

Related Topic