Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting string to double in fluent-nhibernate mapping

I have a sql table with a string column that could contain null, empty string or a double value. I want to map this column to a C# property that is a double, defaulting to zero when the column is null or empty. Can I do this with a fluent-nhibernate mapping? I tried this:

Map(p => p.doubleProperty).CustomSqlType("varchar(20)").CustomType("double").Default("0");

and variations on this theme but I always get an error that the conversion failed.

like image 405
Mike Avatar asked Jul 07 '11 16:07

Mike


2 Answers

For now I've gone with a custom type which allows me to use

      Map(p=>p.doubleProperty).CustomType<DoubleString>();

Which will do for my current needs.

I'll leave the question open for now in case someone comes up with an easier solution.

Code for the DoubleString type is below.

public class DoubleString : IUserType
{
    public new bool Equals(object x, object y)
    {
        if (ReferenceEquals(x, y))
        {
            return true;
        }
        if (x == null || y == null)
        {
            return false;
        }
        return x.Equals(y);
    }

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

    public object NullSafeGet(IDataReader rs, string[] names, object owner)
    {
        var valueToGet = NHibernateUtil.String.NullSafeGet(rs, names[0]) as string;
        double returnValue = 0.0;
        double.TryParse(valueToGet, out returnValue);
        return returnValue;
    }

    public void NullSafeSet(IDbCommand cmd, object value, int index)
    {
        object valueToSet = ((double)value).ToString();
        NHibernateUtil.String.NullSafeSet(cmd, valueToSet, index);
    }

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

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

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

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

    public SqlType[] SqlTypes
    {
        get
        {
            return new[] { new SqlType(DbType.String) };
        }
    }

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

    public bool IsMutable
    {
        get { return true; }
    }
}
like image 115
Mike Avatar answered Sep 19 '22 04:09

Mike


I would just map this to a string and in your entity have a property that is a double that does the conversion. Seems easier and cleaner than doing it in the mapping.

Maybe something like this:

public double Price
{
    get
    {
        double price = -1.0;
        Double.TryParse(stringProperty, out price);
        return price;
    }
    set { stringProperty = value.ToString(); }
}
like image 24
Cole W Avatar answered Sep 22 '22 04:09

Cole W