fluent nHibernate map YesNo when column is nullabl

2019-07-16 04:04发布

问题:

I'm using fluent nHibernate to map a a database flag column "Y"/"N" to bool property:

Map(x => x.Enabled).Column("ENABLED_FLAG").CustomType("YesNo");

The question is, how would one specify how to map a null? Will the null be mapped to true, false, exception?

Update

The default settings seems to map NULL to false. I like that, but still wondering how I could override that to be true?

回答1:

If you want to change the functionality of the null case you would have to create your own custom type - essentially derive from IUserType.

I have done something similar to this with dates (where a 0 date of 01-01-0001 cant save to mssql) and with Guids where we want to insert null instead of Guid.Empty)

Creating your own user type gives the ability to override the NullSafeSet and NullSafeGet methods - which is what you want to do (change the handling of Nulls at read or write) You might even be able to inherit from the original YesNo Type

A good example http://lostechies.com/rayhouston/2008/03/23/mapping-strings-to-booleans-using-nhibernate-s-iusertype/



回答2:

If you want to allow nulls, make your field bool? and it will be null in the database too.