Convert string to double display in free-nhibernate

I have a sql table with a string column that can contain a null, empty row or double value. I want to map this column to the C # property, which is double , defaults to zero when the column is null or empty. Can I do this with a nhibernate smooth transition? I tried this:

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

and variants of this topic, but I always get an error message due to which the conversion failed.

+6
source share
3 answers

For now, I went with a custom type that allows me to use

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

What will do for my current needs.

Now I will leave the question open if someone comes up with an easier solution.

The 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; } } } 
+5
source

I would just match this to a string and there would be a property in your object that is double that does the conversion. It seems easier and cleaner than doing it in cartography.

Maybe something like this:

 public double Price { get { double price = -1.0; Double.TryParse(stringProperty, out price); return price; } set { stringProperty = value.ToString(); } } 
+1
source

I solved the same problem using two properties that both refer to the same private variable. In my example, the database contains varchar, which is NOT USED or ACTUAL, so bool is required for my application.

  private bool _myBool= true; public virtual bool MyBool{ get { return _myBool; } set { _myBool= value; } } public virtual string MyString { get { return _myBool ? "ACTUAL" : "NOT USED"; } set { _myBool= value.Equals("NOT USED"); } } } 
0
source

Source: https://habr.com/ru/post/892253/


All Articles