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.
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; }
}
}
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(); }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With