2

我有一个遗留数据库,它使用存储为 VARCHAR(8) 的零填充数字作为表中的主键值。(例如,“00032982”)

我想将这些映射到我的实体对象中的 Int32 属性而不是字符串。

我的第一次尝试是创建一个实现 IUserType 的类。但是我正在映射一个 ID,而不是一个属性,并且按代码映射不会编译:(也许我没有做那部分对吗?)

Argument 1: cannot convert from 'TestQWebApi.Infrastructure.StringIntUserType' to 'NHibernate.Type.IIdentifierType'

我查看了 IIdentifierType,它有 40 多个成员。我到处看了看,似乎创建一个子类 NHibernate.Type.ImmutableType 的自定义类型将是解决方案。(......也许这是我的第一个错误?)

因此,我创建了一个基于 ImmutableType 的新类,它在 Set() 方法中对其进行零填充:

public class LegacyIntKeyType : ImmutableType, ILiteralType, IDiscriminatorType
{
      public LegacyIntKeyType() : base(SqlTypeFactory.GetString(8))
      {
      }

      public override string Name
      {
        get { return "LegacyIntKeyType"; }
      }

      public override object Get(IDataReader rs, int index)
      {
          try
          {
              return Convert.ToInt32(rs[index]);
          }
          catch (Exception ex)
          {
              throw new FormatException(string.Format("Input string '{0}' was not in the correct format.", rs[index]), ex);
          }
      }

      public override object Get(IDataReader rs, string name)
      {
          try
          {
              return Convert.ToInt32(rs[name]);
          }
          catch (Exception ex)
          {
              throw new FormatException(string.Format("Input string '{0}' was not in the correct format.", rs[name]), ex);
          }
      }

      public override System.Type ReturnedClass
      {
          get { return typeof(Int32); }
      }

      public override void Set(IDbCommand rs, object value, int index)
      {
          ((IDataParameter)rs.Parameters[index]).Value = string.Format("{0:d8}", value.ToString());
      }

      public object StringToObject(string xml)
      {
          return FromStringValue(xml);
      }

      public override object FromStringValue(string xml)
      {
          return Int32.Parse(xml);
      }

          public string ObjectToSQLString(object value, Dialect dialect)
      {
          return value.ToString();
      }

      public override string ToString(object value)
      {
          return value.ToString();
      } 

  }

在我的基础实体类中,我将其定义为 Int32:

public abstract class Entity
{
    public virtual Int32 Id { get; protected set; }
}

然后我尝试映射它:

public class ProcedureMap : ClassMapping<Procedure>
{
    public ProcedureMap()
    {            
        Table("procfile");
        Id(x => x.Id, m =>
        {
          m.Column("key_proced");
          m.Type(new LegacyIntKeyType());
        });
        Property(x => x.Name, m => m.Column("procname"));
    }
}

然后我得到了这个异常......我觉得这可能表明其他东西。这是堆栈跟踪:

[MappingException: Could not determine type for: TestQWebApi.Models.LegacyIntKeyType, TestQWebApi, for columns: NHibernate.Mapping.Column(key_proced)]
   NHibernate.Mapping.SimpleValue.get_Type() +317
   NHibernate.Cfg.XmlHbmBinding.ClassIdBinder.CreateIdentifierProperty(HbmId idSchema, PersistentClass rootClass, SimpleValue id) +301
   NHibernate.Cfg.XmlHbmBinding.ClassIdBinder.BindId(HbmId idSchema, PersistentClass rootClass, Table table) +396
   NHibernate.Cfg.XmlHbmBinding.RootClassBinder.Bind(HbmClass classSchema, IDictionary`2 inheritedMetas) +987
   NHibernate.Cfg.XmlHbmBinding.MappingRootBinder.AddRootClasses(HbmClass rootClass, IDictionary`2 inheritedMetas) +104
   NHibernate.Cfg.XmlHbmBinding.MappingRootBinder.AddEntitiesMappings(HbmMapping mappingSchema, IDictionary`2 inheritedMetas) +165
   NHibernate.Cfg.XmlHbmBinding.MappingRootBinder.Bind(HbmMapping mappingSchema) +117
   NHibernate.Cfg.Configuration.AddDeserializedMapping(HbmMapping mappingDocument, String documentFileName) +244

提前致谢!

4

1 回答 1

1

你必须实现 NHibernates IUserType

class MyIdUserType : IUserType
{
    public object Assemble(object cached, object owner)
    {
        return DeepCopy(cached);
    }

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

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

    bool IUserType.Equals(object x, object y)
    {
        return Object.Equals(x, y);
    }

    public virtual int GetHashCode(object x)
    {
        return (x != null) ? x.GetHashCode() : 0;
    }

    public bool IsMutable { get { return false; } }

    public object NullSafeGet(IDataReader rs, string[] names, object owner)
    {
        return Int32.Parse((string)NHibernateUtil.String.Get(rs, names[0]));
    }

    public void NullSafeSet(IDbCommand cmd, object value, int index)
    {
        NHibernateUtil.String.Set(cmd, string.Format("{0:d8}", value), index);
    }

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

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

    public SqlType[] SqlTypes { get { return new []{ SqlTypeFactory.GetString(8) }; } }
}
于 2012-10-11T12:55:15.837 回答