如何创建/使用Fluent NHibernate约定将UInt32属性自动化为SQL Server 2008数据库?

时间:2010-05-13 13:54:32

标签: nhibernate fluent-nhibernate

我正在尝试使用约定将UInt32属性映射到SQL Server 2008数据库。由于Fluent NHibernate工作方式的更新,我似乎无法根据现有的网络资源创建解决方案 - 即示例已过时。

我正在尝试让NHibernate生成模式(通过ExposeConfiguration)。我很高兴让NHibernate将它映射到任何合理的东西(例如bigint)。

这是我目前的代码(当我尝试公开架构时,由于SQL Server不支持UInt32而失败)。对于代码有点长的道歉,但我不能100%确定与问题相关的内容,所以我在谨慎方面犯了错误。其中大部分内容基于this post

报告的错误是:

System.ArgumentException : Dialect does not support DbType.UInt32

我想我需要一个相对全面的例子,因为我现在似乎无法将各个部分组合成一个有效的解决方案。

FluentConfiguration configuration =
    Fluently.Configure()
        .Database(MsSqlConfiguration.MsSql2008
            .ConnectionString(connectionString))
        .Mappings(mapping =>
            mapping.AutoMappings.Add(
                AutoMap.AssemblyOf<Product>()
                    .Conventions.Add<UInt32UserTypeConvention>()));

configuration.ExposeConfiguration(x => new SchemaExport(x).Create(false, true));

namespace NHibernateTest
{
    public class UInt32UserTypeConvention : UserTypeConvention<UInt32UserType> 
    {
        // Empty.
    }
}

namespace NHibernateTest
{
    public class UInt32UserType : IUserType
    {
        // Public properties.

        public bool IsMutable
        {
            get
            {
                return false;
            }
        }

        public Type ReturnedType
        {
            get
            {
                return typeof(UInt32);
            }
        }

        public SqlType[] SqlTypes
        {
            get
            {
                return 
                    new SqlType[] 
                    { 
                        SqlTypeFactory.Int32 
                    };
            }
        }

        // Public methods.

        public object Assemble(object cached, object owner)
        {
            return cached;
        }

        public object DeepCopy(object value)
        {
            return value;
        }

        public object Disassemble(object value)
        {
            return value;
        }

        public new bool Equals(object x, object y)
        {
            return (x != null && x.Equals(y));
        }

        public int GetHashCode(object x)
        {
            return x.GetHashCode();
        }

        public object NullSafeGet(IDataReader rs, string[] names, object owner)
        {
            int? i = (int?)NHibernateUtil.Int32.NullSafeGet(rs, names[0]);
            return (UInt32?)i;
        }

        public void NullSafeSet(IDbCommand cmd, object value, int index)
        {
            UInt32? u = (UInt32?)value;
            int? i = (Int32?)u;
            NHibernateUtil.Int32.NullSafeSet(cmd, i, index);
        }

        public object Replace(object original, object target, object owner)
        {
            return original;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

当然,您需要映射到现有的SQL Server数据类型。

根据这个问题,"Best way to store UInt32 in Sql Server",您的选择:

  • CLR数据类型
  • bigint
  • decimal
  • 使用int.MinValue映射到int
  • 的解决方法
相关问题