Sometimes you will need a more sophisticated way to translate method calls to HQL. In this recipe, we will show you how to implement a custom LINQ to HQL generator that is able to do this.
CustomLinqGenearatorExample
.NHibernate
and log4net
packages using the NuGet Package Manager Console by executing the following command:Install-Package NHibernate Install-Package log4net
DateTimeFunctionsGenerator
class using the following code:public class DateTimeFunctionsGenerator : BaseHqlGeneratorForMethod { public DateTimeFunctionsGenerator() { SupportedMethods = new[] { ReflectionHelper.GetMethod<DateTime>( d => d.AddDays(0)), ReflectionHelper.GetMethod<DateTimeOffset>( d => d.AddDays(0)), ReflectionHelper.GetMethod<DateTime>( d => d.AddHours(0)), ReflectionHelper.GetMethod<DateTimeOffset>( d => d.AddHours(0)), ReflectionHelper.GetMethod<DateTime>( d => d.AddMinutes(0)), ReflectionHelper.GetMethod<DateTimeOffset>( d => d.AddMinutes(0)), ReflectionHelper.GetMethod<DateTime>( d => d.AddSeconds(0)), ReflectionHelper.GetMethod<DateTimeOffset>( d => d.AddSeconds(0)), ReflectionHelper.GetMethod<DateTime>( d => d.AddMilliseconds(0)), ReflectionHelper.GetMethod<DateTimeOffset>( d => d.AddMilliseconds(0)), }; } public override HqlTreeNode BuildHql( MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor) { return treeBuilder.MethodCall( method.Name, visitor.Visit(targetObject).AsExpression(), visitor.Visit(arguments[0]).AsExpression()); } }
CustomLinqtoHqlGeneratorsRegistry
class using the following code:public class CustomLinqtoHqlGeneratorsRegistry : DefaultLinqToHqlGeneratorsRegistry { public CustomLinqtoHqlGeneratorsRegistry() { this.Merge(new DateTimeFunctionsGenerator()); } }
CustomLinqtoHqlGeneratorsRegistry
into a configuration using the following code:cfg.SetProperty( Environment.LinqToHqlGeneratorsRegistry, typeof (CustomLinqtoHqlGeneratorsRegistry). AssemblyQualifiedName)
In the constructor of DateTimeFunctionsGenerator
, we define the methods that are supported by this HQL generator. In this case, we want to be able to handle AddDays
, AddHours
, AddMinutes
, AddSeconds
, and AddMilliseconds
of DateTime
, and DateTimeOfset types
. We are using ReflectionHelper.GetMethod
to extract the methods from the expression tree.
The BuildHql
method of DateTimeFunctionsGenerator
is responsible for translating our method call to the HQL expression.
Then we register our custom generator in the HQL generator registry. After that we register our custom registry to the configuration.
3.133.157.142