NHibernate - How to store UInt32 in database

和自甴很熟 提交于 2019-12-17 21:35:02

问题


What is the best way to map UInt32 type to sql-server int type with NHibernate.

The value is a picture width/height so negative value are not make sense here.

But maybe I should use int because NHibenate doesn't support unassigned ints.


回答1:


You can map the column with an IUserType.

<class name="UnsignedCounter">
    <property name="Count" type="mynamespace.UInt32Type, mydll"  />
</class>

And the IUserType which maps UInt32? and UInt32.

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 );
    }
}



回答2:


I'm a year late, but since I had the same question and found a different answer I thought I'd add it. It seems simpler. Maybe it has a flaw I haven't discovered yet.

I'm using NHibernate 3.0, Visual Studio 2005, and .NET 2.0.x.

I found I could use .NET's UInt32 class and not include the type attribute in the hbm.xml.

// .NET 2.0 Property syntax
public class MyClass
{
   // NHibernate needs public virtual properties. 
   private UInt32 _Id;
   public virtual UInt32 Id { get { return (_Id); } set { _Id = value; } }
}


// hbml.xml
<class name ="MyClass">
   <id name="Id" />
</class>


// SQL to create the table
CREATE TABLE `PumpConnection` (
`Id` **INT**(10) **UNSIGNED** NOT NULL AUTO_INCREMENT,
)


来源:https://stackoverflow.com/questions/2309072/nhibernate-how-to-store-uint32-in-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!