Reputation: 1017
I am trying to create a Query builder, and I have run into a a bit of a problem. I would like the end user to be able to choose what fields to they would like to be able to select.
my goad is to do something like this
public IQueryable Get(Type entityType)
{
return _dbContext.Set(entityType).AsQueryable();
}
However when I try to do something like this _repository.Get(myType).ToList();
or really anything i do not compile, and get a message like this.
IQueryable' does not contain a definition for 'ToList' and no extension method 'ToList' accepting a first argument of type 'IQueryable' could be found (are you missing a using directive or an assembly reference?)
can someone please help?
Upvotes: 0
Views: 506
Reputation: 39326
You need to use IQueryable<T>
interface instead of IQueryable
. IQueryable<T>
inherits from IEnumerable<T>
, and ToList
is an extension method of IEnumerable<T>
. IQueryable<T>
has other extension methods like ToListAsync
and its overloads.
If you're trying to create a generic repository then define your repository class as generic too. Doing that you could implement Get
this way:
public class Repository<T> : IRepository<T> where T : class,
{
public IQueryable<T> Get()
{
return _dbContext.Set<T>();
}
//...
}
Upvotes: 2
Reputation: 1017
The answer here was that I couldn't use.ToList()
with IQueryable but I could with IQueryable<T>
. So what I had to do was add an Interface to the entities called IEntity
and then do IQueryable<IEntity>().ToList();
Upvotes: 0