1

First of all, I read this article, this one and this one, but I still have a question. So I need a concrete C# solution that solve problem of truncating using any of this solutions: IUserType, interception or ValidationDef. I want to declare fields like this one:

public class MyEntity {
    [Truncate(length=255)]
    public virtual string Comments { get; set; }
}

I need to truncate string line automatically before update/save NHibernate operation. In this case I will not get an exeption System.Data.SqlClient.SqlErrorCollection

String or binary data would be truncated

1 Answer 1

4

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.

1
  • 1
    +1 for class itself, or the business layer. Data layer should not change the business meaning (which truncating of user string is) Commented Dec 10, 2012 at 7:17

Not the answer you're looking for? Browse other questions tagged or ask your own question.