前一段时间使用过Nhibernate,但一直没有研究透。更不用说FluentNHibernate了。
在上次使用的时候,枚举类型的属性在数据库中保存为Int类型字段。那个时候我就直接写成了
<property name="UserType" column="UserType" type="Int32" not-null="true" ></property>
能够正常使用。保存,获取等都能正常对应。但是:在通过CriteriaAPI查询的时候,如果此枚举需要作为条件查询的话,就必须要强制转换成int类型。否则报错。
今天偶尔使用了Example来查询数据,有发生了问题。提示类型不一致。UserType与Int32不一致。
又一次使我了解到,这样设置是不合理的。再次搜素资料,寻求高手。终于得到了答案。
解决方案如下:
1、在Mapping文件中,此属性的type直接不指定。这样NHibernate可以自动匹配到相关的类型。同时生成的数据脚本也是Int类型。保存都是枚举所对应的Int值。
2、可以在此属性的type中直接指定此枚举的全类型,包括assembly。例如:
type="dotNet.DataStatus,dotNet"
这样与1方法类似。所有的操作都能够正常进行。生成的也是Int类型。
但是问题又来了。如果在数据库不是保存int值怎么办?如果保存成字符串呢?比如枚举ToString()后保存。
NH提供了两个类:EnumCharType和EnumStringType来解决这个问题
这里可以参考:http://www.cnblogs.com/jiaxingseng/archive/2010/08/27/1810330.html
如:
public class EnumCharBaz { private Int32 id; private SampleCharEnum type; public virtual Int32 Id { get { return id; } set { id = value; } } public virtual SampleCharEnum Type { get { return type; } set { type = value; } } } public enum SampleCharEnum { On = 'N', Off = 'F', Dimmed = 'D' }
hbm如下:
<class name="EnumCharBaz" table="bc_ecfoobarbaz"> <id name="Id"> <generator class="assigned"/> </id> <property name="Type" column="type" type="NHibernate.Type.EnumCharType`1[[NHibernate.Test.TypesTest.SampleCharEnum, NHibernate.Test]], NHibernate"/> </class>
使用内建的EnumStringType<T>
public class GenericEnumStringClass { public virtual int Id { get; set; } public virtual SampleEnum EnumValue { get; set; } } public enum SampleEnum { On, Off, Dimmed }
hbm如下:
<class name="NHibernate.Test.TypesTest.GenericEnumStringClass, NHibernate.Test" table="bc_estr"> <id name="Id" column="id"> <generator class="assigned" /> </id> <property name="EnumValue" type="NHibernate.Type.EnumStringType`1[[NHibernate.Test.TypesTest.SampleEnum, NHibernate.Test]], NHibernate" column="enumc"/> </class>
如果还不能满足需求,需要自定义的字符串来怎么办?
http://www.cnblogs.com/jiaxingseng/archive/2010/08/27/1810330.html
这位仁兄已经做了介绍,再次就不多废话了。