Does anyone know of a quick way to have NHibernate insert default values for value types as null into the database?
For example:
public class Foo
{
public int SomeProperty { get; set; }
}
By default, int is 0. When it goes into the database, I would like it to go in as null.
I know I could do this by changing SomeProperty to a nullable int, but perhaps there is another way?
I also know that I could do this with an IUserType but is there an easy way of building a user type that can be generically used for all value types?
This is not a simple way to make NHibe convert 0 to null and vice-versa, but an alternative suggestion (maybe or maybe not right in your situation).
Imo, using a default value to mean null is an antipattern; maybe you agree. I take it that you’re trying to hook up some legacy code with a proper database; is that correct?
If you are in control of the business class which you are mapping (class Foo), then I recommend exposing a nullable version of SomeProperty for use moving forward:
You’ll want better names than SomeProperty_new and SomeProperty_old, though.
On the other hand, if 0 is never a valid value (except to mean null), you could instead make the DB use a non-nullable value. It really depends on the situation at hand.