NHibernate中Mapping檔案對應enum欄位

來源:互聯網
上載者:User

    前一段時間使用過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

這位仁兄已經做了介紹,再次就不多廢話了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.