SELECT [quantity ]
,[price]
FROM [dbo].[orderItem]
ORDER BY (quantity * price) DESC
我应该如何编写一个 CreateCriteria 来像上面的例子一样生成 SQL?
SELECT [quantity ]
,[price]
FROM [dbo].[orderItem]
ORDER BY (quantity * price) DESC
我应该如何编写一个 CreateCriteria 来像上面的例子一样生成 SQL?
基于片段,我猜,你已经完成了所有的映射。您还将有类似于此代码段的标准:
var criteria = session
.CreateCriteria<OrderItem>() // class with properties quantity, price ...
.AddOrder(?) // how to append the order
;
var list = criteria.List<OrderItem>(); // Sorted list of OrderItems
唯一缺少的一点是OrderBy
. 感谢 NHibernate 的可扩展性,我们可以创建自己的Order
对象,并且在构建时Criteria
,我们可以调用.AddOrder(CustomOrder...)
下面的代码:
public class CustomOrder : Order
{
public CustomOrder(string propertyName, bool ascending)
: base(propertyName, ascending) { }
public override SqlString ToSqlString(ICriteria criteria
, ICriteriaQuery criteriaQuery)
{
var sqlString = new SqlString(propertyName);
return sqlString.Append(this.ascending ? " asc" : " desc");
}
}
所以,现在我们可以把它们放在一起:
var criteria = session
.CreateCriteria<OrderItem>()
.AddOrder(new CustomOrder("(quantity * price)", false)
;
var list = criteria.List<OrderItem>(); // Sorted list of OrderItems