2011-11-10 48 views
1

我想使用IQueryable檢索特定的記錄。但我得到錯誤'沒有泛型方法'在'類'System.Linq.Queryable'與提供的類型參數和參數兼容。如果方法是非泛型的,則不應提供類型參數。'。我得到了選定的行ID,但我無法顯示出來。這是我的代碼。沒有泛型方法'Where'類型'System.Linq.Queryable'與提供的類型參數和參數兼容

internal static IQueryable GetRecordsFromPrimaryKeys(this IQueryable datasource, List<FilterDescriptor> primaryKeys) 
    { 
     IQueryable data = datasource; 

     ParameterExpression paramExp = null; 
     bool firstLoop = false; 
     System.Linq.Expressions.Expression predicate = null; 

     var RecordType = datasource.GetObjectType(); 
     paramExp = RecordType.Parameter(); 

     foreach (FilterDescriptor primaryKey in primaryKeys) 
     { 
      if (!(firstLoop)) 
      { 
       predicate = data.Predicate(paramExp, primaryKey.ColumnName, primaryKey.Value, FilterType.Equals, false, RecordType); 
       firstLoop = true; 
      } 
      else 
      { 
       predicate = predicate.AndPredicate(data.Predicate(paramExp, primaryKey.ColumnName, primaryKey.Value, FilterType.Equals, false, RecordType)); 
      } 
     } 

     if (paramExp != null && predicate != null) 
     { 
      var lambda = Expression.Lambda(predicate, paramExp); 
      data = data.Provider.CreateQuery(
         Expression.Call(
         typeof(Queryable), 
         "Where", 
         new Type[] { data.ElementType }, 
         data.Expression, 
         lambda 
         ) 
        ); 

     } 

     return data; 
    } 

我的代碼可以很好地用於了IEnumerable/IQueryable的/ ICollection的。但是,當我使用關鍵字virtual指定類並將其鍵入爲ICollection時,它會引發異常。我的代碼是

public class RoomType 
{ 
    public int ID { get; set; } 

    [MaxLength(10, ErrorMessage = "Room code cannot be longer than 10 characters.")] 
    public string Code { get; set; } 

    [MaxLength(50, ErrorMessage = "Room name cannot be longer than 50 characters.")] 
    public string Name { get; set; } 

    public virtual ICollection<RoomCategory> RoomCategories { get; set; } 
} 

當使用關鍵字'virtual'時,一些隨機值被附加到'RecordType'。我認爲這會導致例外。仍在尋找解決方案。

我不知道發生了什麼問題。歡迎任何建議。

謝謝。

+0

我覺得你的代碼應工作。你確定所有的類型都匹配嗎? – svick

回答

1

我剛碰到類似的情況。問題源於這樣的事實:在某些情況下,您正在處理「代理」而不是實際的實體。所以,你想確保RecordType匹配data.ElementType

嘗試:

var recordType = datasource.GetObjectType(); 

// make sure we have the correct type (not the proxy) 
if (recordType.BaseType.Name != "Object") 
    recordType = recordType.BaseType; 

或者更好的,嘗試:

var recordType = data.ElementType 
+0

嘿..謝謝你。它像一個魅力:)。非常感謝!。 – RGR

0

嘗試使用typeof(Enumerable)代替typeof(Quarable)

相關問題