Reputation: 1299
Right now I'm trying to create a generic method for including foreign keys in my repository.
What I currently got is this:
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;
}
}
However when compiling I get the error:
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'
What could be the issue here?
Upvotes: 2
Views: 786
Reputation: 203802
As the error message states, the generic argument to DbSet
must be a reference type. Your generic argument could be anything, including non-reference types. You need to constraint it to just reference types.
Upvotes: 0
Reputation: 25623
Append where T : class
to the end of your method signature:
private static IQueryable<T> IncludeProperties<T>(
this DbSet<T> set,
params Expression<Func<T, object>>[] includeProperties)
where T : class // <== add this constraint.
{
...
}
DbSet<TEntity>
has this constraint, so in order for your T
type argument to be compatible with TEntity
, it must have the same constraint.
Upvotes: 7