我正在将旧式查询CreateCriteria()
重构为QueryOver()
。我的Wcf服务获取string PropertyName
订单查询结果。对于IQueryable
我使用动态LINQ对CreateCriteria()
- AddOrder()
进行此类排序。
IList<object[]> result =
GetSession()
.QueryOver(() => activity)
.JoinAlias(() => activity.ActivityLicense, () => license)
.Select(Projections.ProjectionList()
.Add(Projections.Count<Activity>(e => e.Id), "ActivityCount")
.Add(Projections.Group(() => license.SerialNumber), "SerialNumber")
.Add(Projections.Count<Activity>(e => e.MacAdress), "MacAddressCount")
.Add(Projections.Count<Activity>(e => e.IpAdress), "IpAddressCount")
)
.OrderByAlias("ActivityCount") // Compilation Error - I need such extension method
.List<object[]>();
有关字符串属性名称如何进行排序的任何建议?
PS:我无法使用LINQ到Nhibernate:LINQ to NHibernate - .GroupBy().Skip().Take() cause an exception
谢谢!
答案 0 :(得分:13)
您始终可以获得UnderlyingCriteria
...
var q = GetSession()
.QueryOver(() => activity)
.JoinAlias(() => activity.ActivityLicense, () => license)
.Select(Projections.ProjectionList()
.Add(Projections.Count<Activity>(e => e.Id), "ActivityCount")
.Add(Projections.Group(() => license.SerialNumber), "SerialNumber")
.Add(Projections.Count<Activity>(e => e.MacAdress), "MacAddressCount")
.Add(Projections.Count<Activity>(e => e.IpAdress), "IpAddressCount")
);
q.UnderlyingCriteria.AddOrder(new Order("ActivityCount", true));
var results = q.List();
或作为IQueryOver的扩展方法
public static IQueryOver<T,T> OrderByAlias(this IQueryOver<T,T> q, string aliasName, bool ascending)
{
q.UnderlyingCriteria.AddOrder(new Order(aliasName, ascending));
return q;
}
答案 1 :(得分:1)
您可以通过传入Projections.Property(propName)
直接从QueryOver API设置OrderBy,例如:
var query = GetSession()
.QueryOver<Activity>()
.OrderBy(Projections.Property("ActivityCount").Desc;
无法通过字符串设置方向,因此您必须执行简单的if / else或创建扩展方法以简化API。