在实现自己的IUserType时,如何访问property / mapping-attributes

时间:2015-02-17 09:46:08

标签: c# nhibernate

我已经实现了我自己的类型PaddedString,它在mapping-xml中使用如下:

<?xml version="1.0"
      encoding="utf-8"?>

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                   assembly="MyAssembly"
                   namespace="MyNamespace">
  <class name="MyClass">
    <!-- id is omitted here -->
    <property name="MyProperty"
              length="300"
              type="TypeNamespace.PaddedString, TypeAssembly"/>
  </class>
</hibernate-mapping>

所以,我已按照this great code-project article来实施我的TrimmedString,我认为我可以将此作为PaddedString的指南:

public sealed class PaddedString : IUserType,
                                   IEnhancedUserType
{
    // I am leaving out all the other methods, because NullSafeGet is the only one with the "real" logic
    public object NullSafeGet(IDataReader rs,
                              string[] names,
                              object owner)
    {
        var obj = NHibernateUtil.String.NullSafeGet(rs,
                                                    names[0]);

        var length = 300; // How do I read the attribute `length` of the mapping in here?

        if (obj == null)
        {
            return new string(' ',
                              length);
        }

        return obj.ToString()
                  .PadRight(length,
                            ' ');
    }
}

所需部分非常清楚:如何阅读映射的属性length?或者你知道在PaddedString中注入长度的其他任何方法吗?

1 个答案:

答案 0 :(得分:1)

我通过合并IParameterizedType来解决这个问题:

public sealed class PaddedString : IUserType,
                                   IEnhancedUserType,
                                   IParameterizedType
{
    private int Length { get; set; }

    public void SetParameterValues(IDictionary<string, string> parameters)
    {
        this.Length = int.Parse(parameters["length"]);
    }

    public object NullSafeGet(IDataReader rs,
                              string[] names,
                              object owner)
    {
        var obj = NHibernateUtil.String.NullSafeGet(rs,
                                                    names[0]);

        if (obj == null)
        {
            return new string(' ',
                              this.Length);
        }

        return obj.ToString()
                  .PadRight(this.Length,
                            ' ');
    }
}

然后我就这样使用了:

<?xml version="1.0"
      encoding="utf-8"?>

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                   assembly="MyAssembly"
                   namespace="MyNamespace">
  <class name="MyClass">
    <!-- id is omitted here -->
    <property name="MyProperty">
        <type name="TypeNamespace.PaddedString, TypeAssembly">
            <param name="length">300</length>
        </type>
    </property>
  </class>
</hibernate-mapping>