我试图在NHibernate中包含AddDays,就像那样:
public class ExtendedLinqtoHqlGeneratorsRegistry : DefaultLinqToHqlGeneratorsRegistry
{
public ExtendedLinqtoHqlGeneratorsRegistry()
{
this.Merge(new AddDaysGenerator());
}
}
public class AddDaysGenerator : BaseHqlGeneratorForMethod
{
public AddDaysGenerator()
{
SupportedMethods = new[]
{
ReflectionHelper.GetMethodDefinition<DateTimeOffset?>(d => d.Value.AddDays((double) 0))
};
}
public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor)
{
return treeBuilder.MethodCall("AddDays", visitor.Visit(targetObject).AsExpression(), visitor.Visit(arguments[0]).AsExpression());
}
}
public class MsSql2008CustomDialect : MsSql2008Dialect
{
public MsSql2008CustomDialect()
{
RegisterFunction("AddDays", new SQLFunctionTemplate(NHibernateUtil.DateTime, "dateadd(day,?2,?1)"));
}
}
我的NH配置是:
configuration = new Configuration();
configuration.Proxy(p => p.ProxyFactoryFactory<DefaultProxyFactoryFactory>()).DataBaseIntegration(db =>
{
db.ConnectionStringName = "xxyy";
db.Dialect<MsSql2008CustomDialect>();
})
.AddAssembly(typeof(myClass).Assembly)
.CurrentSessionContext<LazySessionContext>()
.LinqToHqlGeneratorsRegistry<ExtendedLinqtoHqlGeneratorsRegistry>();
尝试将其与谓词一起使用:
var predicate = PredicateBuilder.False<myClass>();
if(...)
predicate = predicate.Or(i => i.MyDate.AddDays(date) > DateTime.Today);
但它不起作用......我总是得到同样的错误:
System.NotSupportedException: System.DateTime AddDays(Double)
at NHibernate.Linq.Visitors.HqlGeneratorExpressionTreeVisitor.VisitMethodCallExpression(MethodCallExpression expression)
知道我做错了什么吗?
由于
答案 0 :(得分:2)
正如评论中所述,您应该检查MyClass.MyDate
是Nullable DateTimeOffset
类型,这是AddDays
声明的目标类型:
SupportedMethods = new[]
{
ReflectionHelper.GetMethodDefinition<DateTimeOffset?>
(d => d.Value.AddDays((double) 0))
};