Skip to content

Commit bf2cc53

Browse files
committed
Support ToString in Linq expressions (NH-2563).
SVN: trunk@5513
1 parent dff8f4b commit bf2cc53

File tree

3 files changed

+51
-1
lines changed

3 files changed

+51
-1
lines changed

Diff for: src/NHibernate.Test/Linq/FunctionTests.cs

+21-1
Original file line numberDiff line numberDiff line change
@@ -90,5 +90,25 @@ where e.FirstName.IndexOf("A") == e.BirthDate.Value.Month
9090

9191
ObjectDumper.Write(query);
9292
}
93-
}
93+
94+
[Test]
95+
public void ToStringFunction()
96+
{
97+
var query = from ol in db.OrderLines
98+
where ol.Quantity.ToString() == "4"
99+
select ol;
100+
101+
Assert.AreEqual(55, query.Count());
102+
}
103+
104+
[Test]
105+
public void ToStringWithContains()
106+
{
107+
var query = from ol in db.OrderLines
108+
where ol.Quantity.ToString().Contains("5")
109+
select ol;
110+
111+
Assert.AreEqual(498, query.Count());
112+
}
113+
}
94114
}

Diff for: src/NHibernate/Linq/Functions/DefaultLinqToHqlGeneratorsRegistry.cs

+1
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ public DefaultLinqToHqlGeneratorsRegistry()
1818
RegisterGenerator(new DictionaryContainsKeyRuntimeHqlGenerator());
1919
RegisterGenerator(new GenericDictionaryItemRuntimeHqlGenerator());
2020
RegisterGenerator(new GenericDictionaryContainsKeyRuntimeHqlGenerator());
21+
RegisterGenerator(new ToStringRuntimeMethodHqlGenerator());
2122

2223
this.Merge(new StartsWithGenerator());
2324
this.Merge(new EndsWithGenerator());

Diff for: src/NHibernate/Linq/Functions/StringGenerator.cs

+29
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
using System;
2+
using System.Collections.Generic;
13
using System.Collections.ObjectModel;
24
using System.Linq.Expressions;
35
using System.Reflection;
@@ -193,4 +195,31 @@ public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject,
193195
}
194196
}
195197

198+
public class ToStringRuntimeMethodHqlGenerator : IRuntimeMethodHqlGenerator
199+
{
200+
private readonly ToStringHqlGeneratorForMethod generator = new ToStringHqlGeneratorForMethod();
201+
202+
public bool SupportsMethod(MethodInfo method)
203+
{
204+
return method != null && method.Name == "ToString" && method.GetBaseDefinition().DeclaringType == typeof(object);
205+
}
206+
207+
public IHqlGeneratorForMethod GetMethodGenerator(MethodInfo method)
208+
{
209+
return generator;
210+
}
211+
}
212+
213+
public class ToStringHqlGeneratorForMethod : IHqlGeneratorForMethod
214+
{
215+
public IEnumerable<MethodInfo> SupportedMethods
216+
{
217+
get { throw new NotSupportedException(); }
218+
}
219+
220+
public HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor)
221+
{
222+
return treeBuilder.MethodCall("str", visitor.Visit(targetObject).AsExpression());
223+
}
224+
}
196225
}

0 commit comments

Comments
 (0)