2012-04-28 23 views
0

我在構建新的對象查詢時遇到了實現TOP或SKIP功能的問題。實體框架 - 使用動態查詢的頂部

我無法使用eSQL,因爲我需要使用「IN」命令 - 如果我遍歷IN並將它們全部添加爲「OR」參數,則這可能會變得非常複雜。

代碼如下:

Using dbcontext As New DB 

     Dim r As New ObjectQuery(Of recipient)("recipients", dbcontext) 
     r.Include("jobs") 
     r.Include("applications") 

     r = r.Where(Function(w) searchAppIds.Contains(w.job.application_id)) 

     If Not statuses.Count = 0 Then 
      r = r.Where(Function(w) statuses.Contains(w.status)) 
     End If 

      If Not dtFrom.DbSelectedDate Is Nothing Then 
       r = r.Where(Function(w) w.job.create_time >= dtDocFrom.DbSelectedDate) 

      End If 

      If Not dtTo.DbSelectedDate Is Nothing Then 
       r = r.Where(Function(w) w.job.create_time <= dtDocTo.DbSelectedDate) 

      End If 

      'a lot more IF conditions to add in additional predicates 

      grdResults.DataSource = r 

     grdResults.DataBind()    

如果我使用任何形式的.TOP或.Skip它拋出一個錯誤:不支持查詢生成方法LINQ to Entities查詢

有什麼辦法使用此方法指定TOP或Limit?如果可能的話,我想避免查詢返回1000條記錄。 (它是一個關於用戶搜索屏幕)

回答

1

不是

r = new ObjectQuery<recipient>("recipients", dbContext)

嘗試

r = dbContext.recipients

.Skip().Take()返回IOrderedQueriable<T>.Where返回IQueriable<T>。因此把.Skip().Take()最後。

也將grdResults.DataSource = r更改爲grdResults.DataSource = r.ToList()以立即執行查詢。這也可以讓你暫時將這一行包裝在try/catch中,這可能會揭示一個更好的信息,說明它爲什麼會出錯。

0

將此標記爲混淆。我應該一直使用.Take而不是.Top或.Limit或任何東西。

我的最後一部分是低於它的工作原理:

grdResults = r.Take(100)