2014-10-10 63 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的一般参数必须是引用类型。您的泛型参数可以是任何东西,包括非参考类型。你需要将它约束为引用类型。