NHibernate/MySQL 字符串连接 [英] NHibernate / MySQL string concatenation

查看:24
本文介绍了NHibernate/MySQL 字符串连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 nhibernate linq 查询,如下所示:

I have a nhibernate linq query that looks like this:

 from b in session.Query<Bookmark>()
where b.Uri.Equals(uri) ||
      b.Uri.Equals("www." + uri) ||
string.Concat("www.", b.Uri).Equals(uri)
select b

这炸了,说不支持 Concat,但是当我将其更改为

This blows up, saying Concat isn't support, but when I change it to

 from b in session.Query<Bookmark>()
where b.Uri.Equals(uri) ||
      b.Uri.Equals("www." + uri) ||
      ("www." + b.Uri).Equals(uri)
select b

它运行良好,但查询如下所示:

It runs fine, but the query looks like this:

select cast(count(*) as SIGNED) as col_0_0_ 
 from bookmarks bookmark0_ 
 where bookmark0_.Uri = 'www.google.com' 
    or bookmark0_.Uri = 'www.www.google.com'
    or 'www.'+bookmark0_.Uri = 'www.google.com';

添加"'www.'+bookmark0_.Uri 而不是 concat('www.',bookmark0_.Uri).有没有办法在 Linq 中为 NHibernate for MySQL 连接字符串?

Where the 'www.'+bookmark0_.Uri is "added" instead of concat('www.',bookmark0_.Uri). Is there a way to concatenate strings in Linq for NHibernate for MySQL?

推荐答案

下面是一个解决这个问题的HqlGenerator:

The following is an HqlGenerator that solves this problem:

public class ConcatHqlGenerator : BaseHqlGeneratorForMethod
{
    public ConcatHqlGenerator()
        : base()
    {
        this.SupportedMethods = new[] 
        { ReflectionHelper.GetMethodDefinition(() => string.Concat(null, null)) };
    }

    public override HqlTreeNode BuildHql(MethodInfo method,
Expression targetObject,
ReadOnlyCollection<Expression> arguments,
HqlTreeBuilder treeBuilder,
IHqlExpressionVisitor visitor)
    {
        return treeBuilder.Concat(
            new[] 
            {
                visitor.Visit(arguments[0]).AsExpression(),
                visitor.Visit(arguments[1]).AsExpression()
            });
    }
}

将此添加到您的 HQLGeneratorsRegistry 中,您将很高兴在 LINQ 语句中调用 string.Concat.

Add this to your HQLGeneratorsRegistry and you will be good to go with calls to string.Concat in you LINQ statements.

public class LinqToHqlGeneratorsRegistry : DefaultLinqToHqlGeneratorsRegistry
{
    public LinqToHqlGeneratorsRegistry()
        : base()
    {
        this.Merge(new ConcatHqlGenerator());
    }
}
private static ISessionFactory CreateSessionFactory()
{
    var configuration = new NHib.Cfg.Configuration();
    configuration.Properties.Add(NHibernate.Cfg
                                           .Environment.LinqToHqlGeneratorsRegistry, 
typeof(LinqToHqlGeneratorsRegistry).AssemblyQualifiedName);
    configuration.Configure();
    return configuration.BuildSessionFactory();
}

这篇关于NHibernate/MySQL 字符串连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆