開篇
用NHibernate持久化類的enum和bool類型的屬性的時候,我們需要持久化的更通用一些,數據庫無關一些。
枚舉持久化為對應整數的字符串,NH默認持久化為整數。
布爾的持久化默認根據數據庫的類型而不同,sqlserver會持久化為bit,可是很多數據庫沒有bit類型,通常用char來持久化。
可以選擇持久化為Y和N,也可以選擇持久化為1和0。
1、枚舉enum的持久化
將枚舉持久化成一個字符串,也就是將枚舉對應的整數持久化到數據庫。
public enum Status
{
Yes = 1,
No = 2
}
public class Product
{
public Product()
{
this.CreateTime = DateTime.Now;
this.ModifyTime = DateTime.Now;
}
public virtual Guid Id { get; set; }
public virtual string Name { get; set; }
public virtual bool Discontinued { get; set; }
public virtual DateTime CreateTime { get; set; }
public virtual DateTime ModifyTime { get; set; }
public virtual Category Category { get; set; }
public virtual int Version { get; set; }
public virtual bool IsDelete { get; set; }
public virtual Status Status { get; set; }
}
直接在column中加入sql-type屬性,設置為數據庫列對應的類型就可以了。
<property name="Status">
<column name="Status" sql-type="varchar(10)" default="1" not-null="true"></column>
</property>
2、布爾bool的持久化
2.1 持久化為Y和N
<property name="IsDelete" type="NHibernate.Type.YesNoType, NHibernate" column="IsDelete">
<column name="IsDelete" sql-type="char(1)" default="0" not-null="true"></column>
</property
使用上面的配置,在數據庫存儲的就是Y和N,代表true和false。
2.2 持久化為1和0
但是我們有時候想要使用1和0代表true和false。
那麼可以先自定義下面的類。
public class YesNo10 : IUserType
{
public bool IsMutable
{
get { return false; }
}
public Type ReturnedType
{
get { return typeof(YesNoType); }
}
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 yesNo = (string)obj;
if (yesNo != "1" && yesNo != "0")
throw new Exception(string.Format ("Expected data to be '1' or '0' but was '{0}'.", yesNo));
return yesNo == "1";
}
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 ? "1" : "0";
}
}
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();
}
}
然後配置成下面的樣子。
<property name="IsDelete" type="Com.Andyshi.NH3.Domain.YesNo10, Com.Andyshi.NH3" column="IsDelete"> <column name="IsDelete" sql-type="char(1)" default="0" not-null="true"></column> </property
type中的內容是“類名, 程序集名”。
本文出自 “突破中的IT結構師” 博客,請務必保留此出處http://virusswb.blog.51cto.com/115214/1229651