Honestly the easiest, most readable solution is to let the class handle it. Something like this:
public class MyEntity {
private string comments;
public virtual string Comments {
get {return comments;}
set {comments = str.Substring(0, Math.Min(value.Length, 255))};
}
}
BUT I don't think that's what you're asking. Other than that you could do something with an IInterceptor that has several methods like OnSave. You would need to write something like this for the method (note this is Psudo code because it's a lot of stuff!):
public boolean OnSave(object entity,
object id,
object[] state,
string[] propertyNames,
IType[] types)
{
for ( int i=0; i<propertyNames.Length; i++ )
{
if ( objectHasAttributeOnproperty(propertyNames[i], Truncate))
{
trucate(entity, propertyNames[i])
return true;
}
}
return true;
}
then register the interceptor with the hibernate session. Every entity that is saved will pass through it and get checked for strings that need to be truncated.
Here is the documentation on interceptors in NHibernate:
http://www.nhforge.org/doc/nh/en/index.html#manipulatingdata-interceptors
Check Stack Overflow for getting Attribute values and calling property setters via reflection.