nhibernate save string in upper case (uppercase)

Asked

Viewed 99 times

2

Hello, is there any nhibernate mapping option to save the fields string on-mode uppercase?

Thank you.

1 answer

0


Yes, defining a UserType customized:

public class UpperString : IUserType
{
    public UpperString()
    {
    }

    #region IUserType Members

    public new bool Equals(object x, object y)
    {
        bool returnvalue = false;
        if ((x != null) && (y != null))
        {
            returnvalue = x.Equals(y);
        }
        return returnvalue;
    }

    public NHibernate.SqlTypes.SqlType[] SqlTypes
    {
        get
        {
            NHibernate.SqlTypes.SqlType[] types = { NHibernate.SqlTypes.SqlTypeFactory.GetString(255) };
            return types;
        }
    }

    public Type ReturnedType
    {
        get
        {
            return typeof(String);
        }
    }

    /// <summary>
    /// Takes care of null values.
    /// </summary>
    public object NullSafeGet(System.Data.IDataReader rs, string[] names, object owner)
    {
        object value = rs.GetValue(rs.GetOrdinal(names[0]));
        if (value == DBNull.Value)
        {
            return String.Empty;
        }
        return value;
    }

    /// <summary>
    /// Faz o UpperCase na sua string sempre que for setar o valor
    /// </summary>
    public void NullSafeSet(System.Data.IDbCommand cmd, object value, int index)
    {
        if (Convert.ToString(value) == String.Empty)
        {
            ((IDataParameter)cmd.Parameters[index]).Value = DBNull.Value;
        }
        else
        {
            //faz o upper
            ((IDataParameter)cmd.Parameters[index]).Value = ((string)value).ToUpper();
        }
    }

    public object DeepCopy(object value)
    {
        return value;
    }

    public bool IsMutable
    {
        get { return true; }
    }

    public object Assemble(object cached, object owner)
    { return DeepCopy(cached); }

    public object Disassemble(object value)
    { return value; }

    public int GetHashCode(object x)
    { return x.GetHashCode(); }

    public object Replace(object original, object target, object owner)
    { return original; }

    #endregion
}

The configuration of Property gets like this:

<property length="24" name="PropriedadeUpper" column="ColunaUpper">
      <type name="MeuAssembly.NHUserTypes.UpperString, MeuAssembly">
      </type>
</property>

I took it from here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.