String comparison with linq?

492 views
Skip to first unread message

emp...@gmail.com

unread,
Jun 10, 2011, 4:48:46 AM6/10/11
to nhusers
Is there built in way to make string comparsion with linq binding ?

like below :

session.Query<Entity>().Where(e => string.Compare("test",e.Name") >
0);

mynkow

unread,
Jun 10, 2011, 6:54:09 AM6/10/11
to nhu...@googlegroups.com
you cannot do this. I also want to use string.Compare() but it is not possible for now.

Andrei

unread,
Jun 10, 2011, 6:31:43 AM6/10/11
to nhusers

Andrei

unread,
Jun 10, 2011, 8:14:52 AM6/10/11
to nhusers
Check http://fabiomaulo.blogspot.com/2010/07/nhibernate-linq-provider-extension.html
.
You can extend the Linq Provider to translate the class to
String.Compare in a HqlNode.
Here is a similar class for Int32.Compare:

public class Int32LinqGenerator : BaseHqlGeneratorForMethod
{
public Int32LinqGenerator()
{
SupportedMethods = new[]
{ ReflectionHelper.GetMethodDefinition<Int32>(x =>
x.CompareTo(Int32.MinValue)) };
}

public override NHibernate.Hql.Ast.HqlTreeNode
BuildHql(System.Reflection.MethodInfo method,
System.Linq.Expressions.Expression targetObject,

System.Collections.ObjectModel.ReadOnlyCollection<System.Linq.Expressions.Expression>
arguments,
NHibernate.Hql.Ast.HqlTreeBuilder treeBuilder,
NHibernate.Linq.Visitors.IHqlExpressionVisitor visitor)
{
HqlExpression nodeTarget =
visitor.Visit(targetObject).AsExpression();
return treeBuilder.Subtract(
nodeTarget,
visitor.Visit(arguments[0]).AsExpression()
);
}
}


Andrei

emp...@gmail.com

unread,
Jun 10, 2011, 8:53:55 AM6/10/11
to nhusers
Hi Andrei,

Thanks for the example however that wouldnt be a very efficient query.
Basically you are making a subtraction then use the equality. For a
simple comparison query that would generate an inefficient query.

On Jun 10, 3:14 pm, Andrei <andreiaga...@gmail.com> wrote:
> Checkhttp://fabiomaulo.blogspot.com/2010/07/nhibernate-linq-provider-exten...

Andrei

unread,
Jun 10, 2011, 11:08:17 AM6/10/11
to nhusers
I agree, the query is not so efficient, but the lambda expression used
for filtering is unusual.
Anyway I think you cannot do better than this because inside the
extension class you don't have access to the "> 0" part, so you cannot
transform it in the optimal GreaterThan, LessThan and so on.
A way to solve in an optimal way this situation is to change the
lambda expression before the query is executed using an
ExpressionVisitor, so you can convert it to a more common lambda
expression using the <, > and = operators. Unfortunately the
DefaultQueryProvider from the NHibernate project doesn't give you the
possibility to modify the lambda expression before it is transformed
in a query (before DefaultQueryProvider.PrepareQuery is called).

Andrei
Reply all
Reply to author
Forward
0 new messages