2009-12-30 98 views
0

我有以下LINQ查詢:用IN運算符LINQ to SQL動態排序?

using (var db = new MyDataContext()) { 
    int[] onlineUsers = GetOnline(); 
    var users = (from u in db.Users orderby 
     (onlineUsers.Contains(u.u_username) && 
     u.u_hasvisible_photo) descending, 
     u.u_lastlogin descending select 
     u.u_username).Skip(startRowIndex). 
     Take(maximumRows).ToList(); 
} 

這工作得很好,併產生使用IN操作符的SQL查詢。

問題是int []中的每個int都通過一個不同的參數傳遞,我知道每個查詢SQL有2100個參數的限制。

我認爲使用LINQ動態庫OrderBy來做排序會更好。

而不是「onlineUsers.Contains(u.u_username)& & u.u_hasvisible_photo)descending」use.OrderBy(orderquery)。

我已經在網上搜索指導或示例來做到這一點,並找不到任何help.Could社區可以幫助我的代碼或鏈接,可以幫助我實現這一點?

回答

0

如果您使用的是SQL Server 2008,則可以創建一個標量函數,該函數需要table-valued parameter,然後像這樣傳遞數組。雖然(你沒有指定你正在使用哪一個(Linq-to-Entities或Linq-to-SQL,而且我假定SQL Server,即使你只是說「sql」 ),所以我不確定如何組合查詢將

你可能想要做的是創建一個table valued user-defined function它採用表值參數(和任何其他參數,你可能有),並通過LINQ公開(你應該能夠創建一個從表值函數的東西可組合),然後從那裏出發。

0

下面是的LINQ to SQL一個例子,它允許您訂購動態。這個例子是使用羅斯文數據庫,你可以簡單地嘗試一下與LinqPad

void Main() 
{ 

    // Demonstrates dynamic ordering 

    var SortExpression = "Total"; // choose ProductName or Total 
    var sortAscending = true; // choose true for ascending, false for descending 

    // the query to sort 
    var data = (from pd in Products 
         join od in OrderDetails on pd.ProductID equals od.ProductID into DetailsByProduct 
         select new { ProductName = pd.ProductName, Total = DetailsByProduct.Count()}).ToList(); 

    // the data source you can use for data binding      
    var ds= (sortAscending) 
     ? data.OrderBy(x => x.GetType().GetProperty(SortExpression).GetValue(x, null)) 
     : data.OrderByDescending(x => x.GetType().GetProperty(SortExpression).GetValue(x, null)); 

    ds.Dump(); 
} 

嘗試通過"ProductName"(可變SortExpression)取代"Total",或作爲排序依據使用false(可變sortAscending)下降。