在fluent-nhibernate映射中将字符串转换为double

Mik*_*ica 6 nhibernate-mapping fluent-nhibernate

我有一个带有字符串列的sql表,可以包含null,空字符串或double值.我想将此列映射到C#属性a double,当列为null或空时默认为零.我可以使用流畅的nhibernate映射吗?我试过这个:

Map(p => p.doubleProperty).CustomSqlType("varchar(20)").CustomType("double").Default("0");
Run Code Online (Sandbox Code Playgroud)

和这个主题的变化,但我总是得到转换失败的错误.

Mik*_*ica 5

现在我已经使用了允许我使用的自定义类型

      Map(p=>p.doubleProperty).CustomType<DoubleString>();
Run Code Online (Sandbox Code Playgroud)

这将满足我目前的需求.

如果有人想出一个更简单的解决方案,我现在就打开这个问题.

DoubleString类型的代码如下.

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; }
    }
}
Run Code Online (Sandbox Code Playgroud)


Col*_*e W 1

我只是将其映射到一个字符串,并且在您的实体中有一个双精度属性来进行转换。看起来比在映射中更容易、更干净。

也许是这样的:

public double Price
{
    get
    {
        double price = -1.0;
        Double.TryParse(stringProperty, out price);
        return price;
    }
    set { stringProperty = value.ToString(); }
}
Run Code Online (Sandbox Code Playgroud)