从数据库中获取包含布尔列的记录时,我遇到了一个问题。我不能改变数据库结构。
数据库类型是字符(1) (PostgreSQL),其中't‘代表true,'f’代表false。我用过PostgreSQLDialect。
我试着把它放到hibernate配置中
<property name="query.substitutions">1 't',0 'f'</property>我试着用方言改写
public override string ToBooleanValueString(bool value)
{
return value ? "t" : "f";
}映射为:
Map(x => x.IsTemplate).Column("template_p");还是不能工作,有帮助吗?
发布于 2011-05-03 19:51:10
您可能需要在此处创建自己的用户类型。下面是一个创建自己的示例:
http://lostechies.com/rayhouston/2008/03/23/mapping-strings-to-booleans-using-nhibernate-s-iusertype/
然后,您的映射将变成如下所示:
Map(x => x.IsTemplate).Column("template_p").CustomType<MyCustomType>();编辑:
您还可以通过对查询替换执行一些操作来使用标准的YesNo类型。我还没有测试过,但可能是这样的:
<property name="query.substitutions">yes 't', no 'f'</property>除了使用YesNo类型之外,您的映射看起来与我上面所述的几乎相同。
发布于 2011-05-04 04:22:19
事实上,Cole W,我做了这个自定义类型,它的效果就像一个护身符
public class TFType : IUserType
{
public bool IsMutable
{
get { return false; }
}
public Type ReturnedType
{
get { return typeof(TFType); }
}
public SqlType[] SqlTypes
{
get { return new[]{NHibernateUtil.String.SqlType}; }
}
public object NullSafeGet(IDataReader rs, string[] names, object owner)
{
var obj = NHibernateUtil.String.NullSafeGet(rs, names[0]);
if(obj == null ) return null;
var truefalse = (string) obj;
if( truefalse != "t" && truefalse != "f" )
throw new Exception(string.Format("Expected data to be 't' or 'f' but was '{0}'.", truefalse));
return truefalse == "t";
}
public void NullSafeSet(IDbCommand cmd, object value, int index)
{
if(value == null)
{
((IDataParameter) cmd.Parameters[index]).Value = DBNull.Value;
}
else
{
var yes = (bool) value;
((IDataParameter)cmd.Parameters[index]).Value = yes ? "t" : "f";
}
}
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 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 == null ? typeof(bool).GetHashCode() + 473 : x.GetHashCode();
}
}发布于 2011-05-03 19:53:33
我还没试过,但也许这能行得通:
Map(x => x.IsTemplate).Formula("case when template_p = 't' then 1 else 0 end")https://stackoverflow.com/questions/5868885
复制相似问题