在NHibernate中将枚举映射为varchar而不是nvarchar

时间:2014-07-15 01:52:28

标签: sql-server nhibernate

在Fluent NHibernate中,是否有人知道是否可以将枚举映射为varchar而不是nvarchar列。

我可以将枚举映射为int或nvarchar,但不能映射到ANSI字符串varchar。

1 个答案:

答案 0 :(得分:1)

在nhibernate中没有内置类型。您可以使用以下类型来实现它:

    [Serializable]
    public abstract class EnumAnsiStringType : AbstractEnumType
    {
        public const int MaxLengthForEnumString = 255;
        protected EnumAnsiStringType(Type enumClass)
            : this(enumClass, MaxLengthForEnumString) { }
        protected EnumAnsiStringType(Type enumClass, int length)
            : base(SqlTypeFactory.GetAnsiString(length), enumClass) { }
        public override string Name
        {
            get { return "enumstring - " + ReturnedClass.Name; }
        }
        public virtual object GetInstance(object code)
        {
            //code is an named constants defined for the enumeration.
            try
            {
                return StringToObject(code as string);
            }
            catch (ArgumentException ae)
            {
                throw new HibernateException(string.Format("Can't Parse {0} as {1}", code, ReturnedClass.Name), ae);
            }
        }
        public virtual object GetValue(object code)
        {
            //code is an enum instance.
            return code == null ? string.Empty : Enum.Format(ReturnedClass, code, "G");
        }
        public override void Set(IDbCommand cmd, object value, int index)
        {
            var par = (IDataParameter)cmd.Parameters[index];
            if (value == null)
            {
                par.Value = DBNull.Value;
            }
            else
            {
                par.Value = GetValue(value);
            }
        }
        public override object Get(IDataReader rs, int index)
        {
            object code = rs[index];
            if (code == DBNull.Value || code == null)
            {
                return null;
            }
            else
            {
                return GetInstance(code);
            }
        }
        public override object Get(IDataReader rs, string name)
        {
            return Get(rs, rs.GetOrdinal(name));
        }
        public override string ToString(object value)
        {
            return (value == null) ? null : GetValue(value).ToString();
        }
        public override object Assemble(object cached, ISessionImplementor session, object owner)
        {
            if (cached == null)
            {
                return null;
            }
            return GetInstance(cached);
        }
        public override object Disassemble(object value, ISessionImplementor session, object owner)
        {
            return (value == null) ? null : GetValue(value);
        }
        public override string ObjectToSQLString(object value, NHibernate.Dialect.Dialect dialect)
        {
            return GetValue(value).ToString();
        }
    }
}