gpt4 book ai didi

c# - 使用 NHibernate 的自定义 Linq 生成器 (AddDays)

转载 作者:行者123 更新时间:2023-11-30 17:01:59 32 4
gpt4 key购买 nike

我试图在 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)

知道我做错了什么吗?

谢谢

最佳答案

如评论中所述,您应该检查 MyClass.MyDate 是否属于 Nullable DateTimeOffset 类型,这是您的 AddDays 的目标类型> 声明:

SupportedMethods = new[]
{
ReflectionHelper.GetMethodDefinition<DateTimeOffset?>
(d => d.Value.AddDays((double) 0))
};

关于c# - 使用 NHibernate 的自定义 Linq 生成器 (AddDays),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20475834/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com