支持NHibernate中的UINt32

时间:2012-07-23 07:38:53

标签: hibernate nhibernate

我正在尝试在我的应用程序中支持UInt32。通过查看此位置的示例,我编写了我的代码。   NHibernate - How to store UInt32 in database。在我的hbm文件中,我定义了属性标记:

           <property name="Uint16Var" column="Uint16Var" 
           type="datatypeSupported.UInt32Type,  datatypeSupported"  />

我还定义了一个像这样的UInt32Type类:

     using System;
     using NHibernate;
     using NHibernate.SqlTypes;
     using NHibernate.UserTypes;

    namespace datatypeSupported
    {
     public class UInt32Type : IUserType
    {

    public object NullSafeGet(System.Data.IDataReader rs, string[] names, object owner)
    {
        int? i = (int?)NHibernateUtil.Int32.NullSafeGet(rs, names[0]);
        return (UInt32?)i;
    }

    public void NullSafeSet(System.Data.IDbCommand cmd, object value, int index)
    {
        UInt32? u = (UInt32?)value;
        int? i = (Int32?)u;
        NHibernateUtil.Int32.NullSafeSet(cmd, i, index);  
    }

    public Type ReturnedType
    {
        get
        {
            return typeof(Nullable<UInt32>);
        }
    }

    public SqlType[] SqlTypes
    {
        get
        {
            return new SqlType[] { SqlTypeFactory.Int32 };
        }
    } public object Assemble(object cached, object owner) 
    { 
        return cached; 
    } 

    public object DeepCopy(object value)
    { 
        return value;
    } 

    public object Disassemble(object value) 
    {
        return value; 
    } 

    public int GetHashCode(object x) 
    { 
        return x.GetHashCode(); 
    }

    public bool IsMutable
    {
        get { return false; }
    } 

    public object Replace(object original, object target, object owner) 
    { 
        return original; 
    } 

    public new bool Equals(object x, object y) 
    { 
        return x != null && x.Equals(y);
    }
}

}

但是当我尝试保存我的实体时,它会出现错误“Dialect不支持DbType.UInt32”。我需要做哪些类型的更改?

1 个答案:

答案 0 :(得分:1)

编写自定义方言,添加对UInt32类型的支持。根据您使用的数据库,继承一种已知的方言。即,对于SQL Server,您可以使用以下内容:

public class CustomMsSqlDialect : MsSql2008Dialect
{
    protected override void RegisterNumericTypeMappings()
    {
        base.RegisterNumericTypeMappings();
        RegisterColumnType(DbType.UInt32, "INT");
    }
}

使用FluentNHibernate注册方言:

Fluently.Configure().Database(
    MsSqlConfiguration.MsSql2008.Dialect<CustomMsSqlDialect>()...)

使用XML:

<property name="dialect">CustomMsSqlDialect, AssemblyName</property>