2014-10-10 48 views
2

現在我試圖創建一個泛型方法來將外鍵包含在我的資源庫中。創建通用擴展方法時的問題

我目前得到了什麼是這樣的:

public static class ExtensionMethods 
{ 
    private static IQueryable<T> IncludeProperties<T>(this DbSet<T> set, params Expression<Func<T, object>>[] includeProperties) 
    { 
     IQueryable<T> queryable = set; 
     foreach (var includeProperty in includeProperties) 
     { 
      queryable = queryable.Include(includeProperty); 
     } 

     return queryable; 
    } 
} 

但是當編譯我的錯誤:

The type 'T' must be a reference type in order to use it as parameter 'TEntity' in the generic type or method 'System.Data.Entity.DbSet'

可能是什麼問題嗎?

回答

7

追加where T : class你的方法簽名的結尾:

private static IQueryable<T> IncludeProperties<T>(
    this DbSet<T> set, 
    params Expression<Func<T, object>>[] includeProperties) 
    where T : class // <== add this constraint. 
{ 
    ... 
} 

DbSet<TEntity>有這個限制,所以爲了您的T類型參數與TEntity兼容,它必須具有相同的約束。

+0

啊我現在看到了。非常感謝你的幫助! – JensOlsen112 2014-10-10 20:48:55

0

如錯誤消息所示,DbSet的一般參數必須是引用類型。您的泛型參數可以是任何東西,包括非參考類型。你需要將它約束爲引用類型。