I have an IQueryable
that I add Where
clauses to according to search parameters. At the moment, this queries the database so is of type Music
(IQueryable<Music>
).
I have realised that I have a cache of the approved rows of this data (i.e. where the rows have the approved flag set to true).
So to be more efficient, I thought I would to search the cache rather than the database. The cache hold the same records but they have been converted to DTOs so would be an IQueryable<MusicDTO>
.
I have tried this:
if (search.Approved == true)
{
IQueryable<MusicDTO> query = Cache.regetCachedMusics().AsQueryable();
}
else
{
IQueryable<Music> query = DBContext.Musics;
}
if (search.ID.HasValue)
query = query.Where(x => x.ID == search.ID); //There are more of these
This doesn’t allow me to add the where clause as it says the query doesn’t exist.
So I tried:
IQueryable<dynamic> query;
if (search.Approved == true)
{
query = Cache.regetCachedMusics().AsQueryable();
}
else
{
query = DBContext.Musics;
}
if (search.ID.HasValue)
query = query.Where(x => x.ID == search.ID); //There are more of these
But this doesn’t work because the x.ID == Search.ID
throws
An expression tree may not contain a dynamic operation
Is this possible somehow, or is it more hassle than it’s worth?
3
If code must be structured this way, you could create an interface that has an ID property, like so:
public interface IMusic
{
int ID { get; set; }
}
If both Music
and MusicDTO
implement this interface, you could do like so:
IQueryable<IMusic> query;
if (search.Approved)
{
query = Cache.regetCachedMusics().AsQueryable();
}
else
{
query = DBContext.Musics;
}
if (search.ID.HasValue)
{
query = query.Where(x => x.ID == search.ID);
}