Thursday, February 25, 2016

Unintended NHibernate Update

I encountered a strange error wherein NHibernate UPDATE an entity even I'm just selecting it from Linq.

The nature of the problem is similar to this stackoverflow question: http://stackoverflow.com/questions/2001297/nhibernate-doing-updates-on-select/2001389#2001389


Though it's similar, it befuddled me for a while as I thought there's a flaw on my implementation of custom Jsonb .NET type for Postgresql.

I tried commenting all properties that uses Jsonb type, still there's an UPDATE when just selecting an entity.

When I'm down to few properties and commented them, the DateTime type, the unintended UPDATE error is gone.

The error is in the default value of non-null DateTime, if it's not explicitly assigned, the default value is 0001-01-01, so that's what gets saved to the database. That makes NHibernate wonky when reading the entity again, the pushed value to DateTime type and the read value become different.

The timestamp column is not nullable and have a default value of CURRENT_TIMESTAMP, so I thought it's prudent to make the corresponding property on application (.NET) a not nullable type too. There's a problem with making the .NET type non-nullable, if the value is forgotten to be explicitly assigned a value (e.g., DateTime.Now) in the application, the value that will get saved to database is 0001-01-01 since it's the default value of DateTime when it's not assigned a value.


To conclude, it's better to make the .NET DateTime type nullable even if the underlying datetime type is not nullable, so when it's forgotten to be assigned a value, what will be saved to database will be null, and since the timestamp column in the table is not nullable, it will throw an exception, it will fail fast, early error, early fix, no corrupt data.


Happy Coding!

No comments:

Post a Comment