NHIBERNATE - Come archiviare UINT32 nel database
-
22-09-2019 - |
Domanda
Qual è il modo migliore per mappare il tipo Uint32 al tipo SQL-Server Int con nhibernate.
Il valore è una larghezza/altezza dell'immagine, quindi il valore negativo non ha senso qui.
Ma forse dovrei usare INT perché Nhibenate non supporta INT non assegnati.
Soluzione
Puoi mappare la colonna con un iusertype.
<class name="UnsignedCounter">
<property name="Count" type="mynamespace.UInt32Type, mydll" />
</class>
E l'iusertype che mappe UInt32?
e 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 );
}
}
Altri suggerimenti
Sono in ritardo di un anno, ma da quando ho avuto la stessa domanda e ho trovato una risposta diversa, ho pensato di aggiungerla. Sembra più semplice. Forse ha un difetto che non ho ancora scoperto.
Sto usando NHIBERNATE 3.0, Visual Studio 2005 e .NET 2.0.X.
Ho scoperto che potrei usare la classe Uint32 di .NET e non includere l'attributo di tipo in 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,
)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow