c# – NHibernate / MySQL字符串连接

我有一个看起来像这样的nhibernate linq查询:from b in session.QueryBookmark()where b.Uri.Equals(uri) ||b.Uri.Equals(www. + uri) ||string.Concat(www., b.Uri).Equals(uri)select b这个爆炸,说康卡特...

我有一个看起来像这样的nhibernate linq查询:

 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

这个爆炸,说康卡特不支持,但当我改变它

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

它运行正常,但查询如下所示:

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 for NHibernate for MySQL中连接字符串?

解决方法:

以下是解决此问题的HqlGenerator:

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.

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();
}

本文标题为:c# – NHibernate / MySQL字符串连接

基础教程推荐