在Fluent NHibernate映射中,将字符串转换为double可以通过自定义转换器实现。以下是一个示例:
首先,创建一个自定义转换器:
public class StringToDoubleConverter : IUserType
{
public new bool Equals(object x, object y)
{
return object.Equals(x, y);
}
public int GetHashCode(object x)
{
return x.GetHashCode();
}
public object NullSafeGet(IDataReader rs, string[] names, object owner)
{
object obj = NHibernateUtil.String.NullSafeGet(rs, names[0]);
if (obj == null)
{
return null;
}
return Convert.ToDouble(obj.ToString(), CultureInfo.InvariantCulture);
}
public void NullSafeSet(IDbCommand cmd, object value, int index)
{
if (value == null)
{
((IDataParameter)cmd.Parameters[index]).Value = DBNull.Value;
}
else
{
((IDataParameter)cmd.Parameters[index]).Value = value.ToString();
}
}
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 cached;
}
public object Disassemble(object value)
{
return value;
}
public SqlType[] SqlTypes
{
get
{
return new[] { new SqlType(DbType.String) };
}
}
public Type ReturnedType
{
get
{
return typeof(double);
}
}
public bool IsMutable
{
get
{
return false;
}
}
}
然后,在Fluent NHibernate映射中使用自定义转换器:
public class MyEntityMap : ClassMap<MyEntity>
{
public MyEntityMap()
{
Table("MyEntity");
Id(x => x.Id).GeneratedBy.Identity();
Map(x => x.MyDoubleProperty).CustomType<StringToDoubleConverter>().Not.Nullable();
}
}
这样,在映射MyEntity实体时,MyDoubleProperty属性将使用自定义的StringToDoubleConverter转换器,将字符串转换为double类型。
领取专属 10元无门槛券
手把手带您无忧上云