2014-04-29 54 views
2

空我有這樣的方法:值不能在LINQ條款

protected async Task<List<T>> Get<T>(Expression<Func<T, bool>> select) where T : class, IEntity 
{ 
    var query = Context.Set<T>(); 
    query = query.Where(select); 
    return await query.ToListAsync<T>(); 
} 

我這樣稱呼它:

var result = await Get<T>(a => a.Id == myId); 

但Get方法不斷拋出「值不能爲空。參數:source'。

我錯過了什麼?

更新1:
StackTrace: at System.Data.Entity.Utilities.Check.NotNull[T](T value, String parameterName) at System.Data.Entity.QueryableExtensions.ToListAsync[TSource](IQueryable'1 source) at SoccerPool.MVC5.Models.Config.BaseApiController.<Get>d__49'1.MoveNext() in c:\Projects\SoccerPool\SoccerPool.MVC5\Models\Config\BaseApiController.cs:line 190

更新2:
Context.Set<T>() is not null. It contains 48 records if I don't perform the linq query. And 'Context' is a property which returns an instance of my DbContext.

+0

您可以添加堆棧跟蹤嗎? –

+1

你能解釋一下你如何填充'Context.Set ()',因爲錯誤提示'query'爲空 – jaywayco

回答

0

Context.Set可能是零。

此外,請使用同步代碼而不是異步進行測試,也許問題在於過早的資源配置。

請提供完整的堆棧跟蹤來確定,並解釋我們如何運作您的datacontext(獲取方法)。

0

我顯然欺騙了你們。我最真誠的道歉。

在創建一個同步版本後,Richard建議我注意該方法中的'query'爲null。所以這個例外是有道理的。

在試圖闡明的代碼SO我除去以下的(除其他東西):

protected async Task<List<T>> Get<T>(
    Expression<Func<T, bool>> select) where T : class, IEntity 
{ 
    var query = Context.Set<T>() as DbSet<T>; 
    query = query.Where(select) as DbSet<T>; 
    return await query.ToListAsync<T>(); 
} 

注意「作爲DbSet」。這適用於Context.Set,但不適用於返回IQueryable的'.Where',這是我未知的原因,不能轉換爲DbSet。 (我認爲它從IQueryable繼承)。

因此'as DbSet'使查詢爲空,從而浪費您所有的時間。

謝謝你放縱我。

+0

你應該把這個標記爲答案,所以人們不會試一試。 – i3arnon

+0

剛剛嘗試過,但我可以在兩天內完成。所以它看起來。 –