NHibernate IUserType和HQL和Linq的自定义函数

时间:2018-10-25 14:19:53

标签: c# linq nhibernate fluent-nhibernate

简而言之,我想创建一个自定义IUserType来表示.NET中的IPAddress(作为inet中的postgresql类型)并能够使用通过HQLLinq的自定义函数。我无法为Linq实现自定义功能。

到目前为止我所拥有的:

A)我可以映射它:

public class SomeEntityMapper : ClassMap<SomeEntity> {
   public SomeEntityMapper() {
       ...
       Map(x => x.IpAddressField)
                 .CustomSqlType("inet")
                 .CustomType<IPAddressUserType>()
       ...
   }
}

下面的IUserType实现:

[Serializable]
public class IPAddressUserType : IUserType
{
    public new bool Equals(object x, object y)
    {
        if (x == null && y == null)
            return true;

        if (x == null || y == null)
            return false;

        return x.Equals(y); 
    }

    public int GetHashCode(object x)
    {
        if (x == null)
            return 0;

        return x.GetHashCode();
    }

    public object NullSafeGet(DbDataReader rs, string[] names, ISessionImplementor session, object owner)
    {
        if (names.Length == 0)
            throw new InvalidOperationException("Expected at least 1 column");

        if (rs.IsDBNull(rs.GetOrdinal(names[0])))
            return null;

        object value = rs[names[0]]; 

        return value;
    }

    public void NullSafeSet(DbCommand cmd, object value, int index, ISessionImplementor session)
    {
        NpgsqlParameter parameter = (NpgsqlParameter) cmd.Parameters[index];
        parameter.NpgsqlDbType = NpgsqlTypes.NpgsqlDbType.Inet;

        if (value == null)
        {
            parameter.Value = DBNull.Value;
        }
        else
        { 
            parameter.Value = value;
        }
    }

    public object DeepCopy(object value)
    {
        if (value == null)
            return null;

        IPAddress copy = IPAddress.Parse(value.ToString());
        return copy;
    }

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

    public object Assemble(object cached, object owner)
    {
        if (cached == null)
            return null;

        if (IPAddress.TryParse((string)cached, out var address))
        {
            return address;
        }

        return null;
    }

    public object Disassemble(object value)
    {
        if (value == null)
            return null;

        return value.ToString();

    }

    public SqlType[] SqlTypes => new SqlType[] { new NpgsqlSqlType(DbType.String, NpgsqlTypes.NpgsqlDbType.Inet),  };

    public Type ReturnedType => typeof(IPAddress);

    public bool IsMutable => false;
}

public class NpgsqlSqlType : SqlType
{
    public NpgsqlDbType NpgDbType { get; }

    public NpgsqlSqlType(DbType dbType, NpgsqlDbType npgDbType)
        : base(dbType)
    {
        NpgDbType = npgDbType;
    }

    public NpgsqlSqlType(DbType dbType, NpgsqlDbType npgDbType, int length)
        : base(dbType, length)
    {
        NpgDbType = npgDbType;
    }

    public NpgsqlSqlType(DbType dbType, NpgsqlDbType npgDbType, byte precision, byte scale)
        : base(dbType, precision, scale)
    {
        NpgDbType = npgDbType;
    }
} 

}

B)我可以使用HQL和我实现的自定义函数(inet_equals)对其进行查询。

using(var session = _factory.OpenSession()) {
   var q = session.CreateQuery("from SomeEntity as s WHERE inet_equals(s.IpAddressField, :ip)"); 
       q.SetParameter("ip", IPAddress.Parse("4.3.2.1"), NHibernateUtil.Custom(typeof(IPAddressUserType)));
}

自定义Postgresql方言扩展了以下HQL函数实现:

 public class CustomPostgresqlDialect : PostgreSQL83Dialect
    {
        public CustomPostgresqlDialect()
        {
            RegisterFunction("inet_equals", new SQLFunctionTemplate(NHibernateUtil.Boolean, "(?1::inet = ?2::inet)"));
        }
    }

C),我希望能够使用LINQ像这样查询它:

using(var session = _factory.OpenSession()) {
   var q = session.Query<SomeEntity>()
           .Where(s => s.IpAddressField.InetEquals(IPAddress.Parse("4.3.2.1")));
   } 

下面为NHibernate提供程序定制的LINQ生成器:

 public static class InetExtensions
    {
        public static bool InetEquals(this IPAddress value, IPAddress other)
        {
            throw new NotSupportedException();
        }  
    }

    public class InetGenerator : BaseHqlGeneratorForMethod
    {
        public InetGenerator()
        {
            SupportedMethods = new[]
            {
                ReflectHelper.GetMethodDefinition(() => InetExtensions.InetEquals(default(IPAddress), default(IPAddress))) 
            };
        } 
        public override HqlTreeNode BuildHql(MethodInfo method, System.Linq.Expressions.Expression targetObject, ReadOnlyCollection<System.Linq.Expressions.Expression> arguments,
            HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor)
        {
            HqlExpression lhs = visitor.Visit(arguments[0]).AsExpression();
            HqlExpression rhs = visitor.Visit(arguments[1]).AsExpression(); 

            return treeBuilder.BooleanMethodCall(
                "inet_equals",
                new[]
                {
                    lhs,
                    rhs 
                }
            );
        }
    }

    public class ExtendedLinqToHqlGeneratorsRegistry :
        DefaultLinqToHqlGeneratorsRegistry
    {
        public ExtendedLinqToHqlGeneratorsRegistry()
            : base()
        {
            this.Merge(new InetGenerator());
        }
    }

不幸的是,在使用LINQ时出现了此异常:

HibernateException: Could not determine a type for class: System.Net.IPAddress

有趣的是,如果我在NHibernateUtil.Custom(typeof(IPAddressUserType))查询中省略了HQL参数,就会得到完全相同的错误。

这使我相信自己走在正确的道路上,但是我无法弄清楚我可能会错过什么。我假设我需要通知Generator内的NHibernate这是一个自定义UserType(就像我通过HQL参数对NHibernateUtil.Custom(typeof(IPAddressUserType))查询所做的一样。

2 个答案:

答案 0 :(得分:1)

我找到了解决方法。

要提示NHibernate使用正确的UserType,请使用:MappedAs扩展方法,如下所示:

using(var session = _factory.OpenSession()) {
   var q = session.Query<SomeEntity>()
           .Where(s => s.IpAddressField.InetEquals(
                 IPAddress.Parse("4.3.2.1").MappedAs(NHibernateUtil.Custom(typeof(IPAddressUserType))
            );

}

答案 1 :(得分:0)

今年是2019年,我仍然停留在版本 3.3.2.GA的NHibernate 上,MappedAs扩展名方法仅存在于版本 4.x 起。

我的情况是需要将大字符串作为参数传递给HqlGeneratorForMethod中受支持的方法。

我创建了以下类来存储任何大字符串,以用作整个应用程序中任何方法的参数:

public class StringClob
{
    public StringClob()
    {
    }

    public StringClob(string value)
    {
        Value = value;
    }

    public virtual string Value { get; protected set; }
}

为了将NHibernateUtil.StringClob类型与string值进行链接,我想到了为我的类创建一个映射,而不只通知表映射该属性(我使用FluentNHibernate来映射类):

public class StringClobMap : ClassMap<StringClob>
{
    public StringClobMap()
    {
        Id(x => x.Value, "VALUE").CustomType("StringClob").CustomSqlType("VARCHAR(MAX)").Length(int.MaxValue / 2);
    }
}

现在假设按照@krdx的示例,用法如下:

using(var session = _factory.OpenSession()) 
{
    var q = session.Query<SomeEntity>()
                   .Where(s => s.IpAddressField.InetEquals(new StringClob("<large_string_here>")));

    // ...
}

因此,通过传递StringClob类作为参数,NHibernate获得了映射中定义的自定义类型。

我希望我能帮助仍然使用 NHibernate 3.3.2.GA 的人。