2012-08-13 75 views
6

我正在重構舊式查詢CreateCriteria()QueryOver()。我的Wcf服務獲取string PropertyName以訂購查詢結果。對於IQueryable我使用Dynamic LINQ來做這樣的排序,對於CreateCriteria() - AddOrder()Nhibernate QueryOver。 OrderBy使用字符串屬性名稱。

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

謝謝!

回答

12

你總是可以得到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; 
} 
+0

謝謝。是否有可能將ICriteria變回IQueryOver? – 2012-08-13 16:08:35

+0

我不這麼認爲,你可以做的是重構成IQueryOver擴展方法。我會舉例... – dotjoe 2012-08-13 16:36:07

0

擴展方法,您可以直接從QueryOver API通過傳遞Projections.Property(propName)設置的排序依據,爲例如:

var query = GetSession() 
       .QueryOver<Activity>() 
       .OrderBy(Projections.Property("ActivityCount").Desc; 

有沒有辦法s通過一個字符串來確定方向,所以你必須做一個簡單的if/else或者創建一個擴展方法來簡化API。

+0

.Desc屬性不存在 – 2016-09-13 05:09:49