NHibernate Pitfalls: Specifying Property Types
This is part of a series of posts about NHibernate Pitfalls. See the entire collection here.
When you want to specify an NHibernate type (implementation of NHibernate.Type.IType) for a property using mapping by code, you might be tempted to do something like this:
1: ca.Property(x => x.SomeProperty, x =>
2: {
3: x.Type<StringClobType>();
4: });
If you try this, you will get a nasty exception about the type not having a public parameterless constructor. Ouch!
The thing is: NHibernate types are supposed to be stateless, and therefore it does not make sense to have several instances of a type, that is why NHibernate encourages us to use the static fields defined in the NHibernateUtil class and that is also why most of the built-in types don’t have a public parameterless constructor.
So, if you want to implement your own types, you can certainly add a public parameterless constructor to them and use the above syntax, but if you are going to use the built-in types, you should instead use:
1: ca.Property(x => x.SomeProperty, x =>
2: {
3: x.Type(NHibernateUtil.StringClob);
4: });