NHibernate CompositeUserType: How to specify Sql types?

Using NH 2.0, I have my own type. It has four properties, so I implemented ICompositeUserType .

I want to specify the length and precision for string and decimal properties inside a custom type, so as not to indicate it each time it is used in mapping files.

But for implementation, there is only the PropertyTypes property, which returns I print. The funny thing is: IUserType has the SqlTypes property, ICompositeUserType not.

  • Do I need to implement both interfaces?
  • Do I have to implement a user type to wrap each sql type that I want to specify?
  • Or how can I specify the Sql type for a composite user type?

Thank you very much.

+4
source share
2 answers

I found a solution, it is quite simple. I have to create NHibernate types using TypeFactory :

 public IType[] PropertyTypes { get { return new [] { TypeFactory.GetDecimalType(36, 18), TypeFactory.GetStringType(100) } } } 
+1
source

I recommend downloading the source code for this type of digging (NH 2.0).

First, consider the TypeFactory.HeuristicType method, which creates an instance of IType.

 ... else if (typeof(ICompositeUserType).IsAssignableFrom(typeClass)) { type = new CompositeCustomType(typeClass, parameters); } else if (typeof(IUserType).IsAssignableFrom(typeClass)) { type = new CustomType(typeClass, parameters); } ... 

So, if your custom type implements ICompositeUserType, it gets an instance of the CompositeCustomType class. This eliminates the possibility of implementing the ICompositeUserType and IUserType interfaces.

Now consider CompositeCustomType

 public override SqlType[] SqlTypes(IMapping mapping) { IType[] types = userType.PropertyTypes; SqlType[] result = new SqlType[GetColumnSpan(mapping)]; int n = 0; for (int i = 0; i < types.Length; i++) { SqlType[] sqlTypes = types[i].SqlTypes(mapping); for (int k = 0; k < sqlTypes.Length; k++) { result[n++] = sqlTypes[k]; } } return result; } 

This way your types are returned from PropertyTypes and build SqlType for each property. This means that providing your own custom type types for each property will do the trick.

+3
source

All Articles