NHibernate: 使用HQL和UserTypes作为查询参数

4

我使用的数据库有一个奇怪的日期格式。我编写了一个 UserType 来将标准 .NET DateTime 转换到/从奇怪的格式,它运行得很好。

通常我会使用 ICriteria 查询,但决定在这个项目中尝试使用 HQL 的 IQuery。我遇到了一个问题,查询不会将参数转换为适当的 UserType。

例如:

IQuery query = session.CreateQuery("from OfflineShipmentLineItem as line join fetch line.Shipment as shipment join fetch line.Extension where shipment.ShipmentDate = :date");
query.SetParameter("date", date);

return query.List<OfflineShipmentLineItem>();

上面的代码出错是因为查询 shipment.ShipmentDate 的结果是 '4/28/2009 12:00:00',而不是 UserType 格式。
如果使用 ICriteria,就可以正常工作:
ICriteria criteria = session.CreateCriteria(typeof(OfflineShipmentLineItem));

criteria.SetFetchMode("Shipment", FetchMode.Eager);
criteria.SetFetchMode("Extension", FetchMode.Eager);

criteria.CreateAlias("Shipment", "shipment");

criteria.Add(Expression.Eq("shipment.ShipmentDate", date));

return criteria.List<OfflineShipmentLineItem>();

一切都正常工作,因为使用了shipment.ShipmentDate的UserType将日期进行了翻译。
我是否忽略了一些指示HQL应该做什么的东西?
1个回答

7

我没有时间自己尝试,但请尝试添加SetParameter的第三个参数(IType)。作为参数,请使用NHUtils.Custom(typeof(YourIUserType))。


你太棒了,成功了!我不确定我是怎么错过那个的。我想肯定有办法帮助HQL找出该做什么。 - anonymous
这种行为在NH 2.1.2中改变为“做正确的事情”(像Criteria一样调用IUserType),但是您的提示解决了我在2.1.0上遇到的问题(由于各种原因,我被困在这个版本)。非常感谢! - Nicholas Piasecki

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接