现在我正在尝试创建一个通用方法来在我的存储库中包含外键。
我目前得到的是这个:
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'
这可能是什么问题?
最佳答案
追加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
兼容的类型参数,它必须具有相同的约束。
关于c# - 创建通用扩展方法时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26307700/