views:

77

answers:

3

I read with excitement the first article that popped up in google -- it was exactly my problem. I have an object model with a non-null date field, but the underlying database field was nullable, and had a null value. It was a DateTime. nHibernate set the value to .Net's Date.MinValue, then tried to save it back, yielding an error.

The solution in the article: Simply use "DateTime?" in the domain model.

That won't work for us.

Here's the thing: We're doing a major refactor, which includes data migrations from one schema to another, moving from ADO to nHibernate, etc., complex stuff. Bottom line: The object model is correct as it is, it's NOT a nullable DateTime (A "CreatedDate"). Setting it to DateTime? would work technically, but it's wrong domain-ly. What I REALLY want is for nHibernate to stop being so helpful and just throw an error when it runs across an attempt to load a null DateTime into a non-nullable domain object. I believe this will help us to identify these issues much more quickly.

I know nHibernate is highly configurable/mappable... is there a way to achieve this behavior, and what's the best way to do it...?

Thanks in advance for any help!

A: 

It sounds like the column itself should actually not be nullable in the database. One thing I've seen in the past is to default the "CreateDate" column to getdate() in the database. You could also implement a trigger to set the CreateDate to getdate() when a record is inserted. If you use the default, the value will be set when the record is inserted (as long as you don't explicitly pass one in), and Hibernate should be able to return it to you after the save, or the next time you lookup the record.

Andy White
Thanks for your quick response, Andy.I agree that the correct solution is to make those database fields non-nullable. The thing is that we're doing a major refactor of a large database and it appears we've made a few fields nullable that shouldn't be. I was hoping that getting nHibernate to throw an error in a nullable/non-nullable mismatch case like this would help us to identify the fields we missed.
Edward Buatois
A: 

The best solution is to make the field non-nullable in the database. Is there a reason you can't do that? It's important that nullability in your domain model matches the database schema.

I don't know of a way to set this behavior by configuration. If this affects a few fields you can hide the problem by mapping a private field and controlling it through a property but this won't give you an exception on load. To do that you would have to write an implementation of ILoadEventListener (I think that's the right one, I've never done it).

Jamie Ide
+1  A: 

Is DateTime.MinValue a useful value for you?

Can't you simply implement the setter and throw an exception when you get that value?

Lasse V. Karlsen