NH枚举实体枚举值存为字串

    技术2025-10-21  16

    NH枚举实体枚举值存为字串

    前言:枚举值存默认我们知道保存是整形,实际上这是没有什么意义的,如何让其有意义呢?

    那么就将其保存为字串吧,下面的步骤用nh3慢慢将其实现

    1:实体(程序集为Eg.Core)

    public enum AccountTypes

        {

            Consumer,

            Business,

            Corporate,

            NonProfit

        }

     

        public class Account

        {

            public virtual Guid Id { get; set; }

            public virtual AccountTypes AcctType { get; set; }

            public virtual string Number { get; set; }

            public virtual string Name { get; set; }

    }

    2:映射

    <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"

        assembly="Eg.Core"

        namespace="Eg.Core">

      <class name ="Account">

      <id name="Id">

        <generator class="guid.comb" />

      </id>

      <natural-id>

        <property name="Number" not-null="true"  />

      </natural-id>

      <property name="Name" not-null="true" />  

        <!--关键地方注意type类型-->

      <property name="AcctType" not-null="true"

                 type="NHibernate.Type.EnumStringType`1[[Eg.Core.AccountTypes, Eg.Core]], NHibernate"

                />

      </class>

    </hibernate-mapping>

    3:其他配置略

    4:单元测试

    [Test]

            public void CreateAccount()

            {

                //save

                NHibernateHelper.BeginTransaction();

                Account ac = new Account()

                {

                    AcctType = AccountTypes .Corporate  ,

                    Name ="abcName",

                    Number ="210403033"

                };

                NHibernateHelper.Session.Save(ac);

                NHibernateHelper.CommitTransaction();

                NHibernateHelper.CloseSession();

           

                //load

                Account acGet=NHibernateHelper.Session.Get<Account>(ac.Id);

                Console.WriteLine("AcctType(int):" + (int)acGet.AcctType + "; AcctType(str)"+acGet .AcctType );

            }

    结果显示:

    AcctType(int):2; AcctType(str)Corporate

    5:源代码下载:

    http://download.csdn.net/source/3024057

     

    最新回复(0)