Reputation: 10889
I am using Entity Framework and have to query a "Project" property a lot, which has a lot of properties which have to be included in the query, making the query bloated:
var project = await this.ProjectRepository.GetRaw().Where(x => x.ID == id).Include(x => x.Leader).Include(x => x.Users).Include(x => x.Firm).FirstOrDefaultAsync();
Please not that GetRaw() returns a IQueryable
Is there a way to construct some helper method where the "include" portion is added, while I dynamically pass in the rest of the query?
something like that:
public async Task<List<Project>> GetProjects(query)
{
return this.ProjectRepository.GetRaw().Include(x => x.Leader).Include(x => x.Users).Include(x => x.Firm) + query;
}
usage something like that:
public ProjectController
{
public void Test()
{
var result = GetProjects.Where(x => x.ID == 0).FirstOrDefaultAsync();
}
}
Upvotes: 1
Views: 46
Reputation: 1728
I think it should look more like this:
public ObjectQuery<Project> GetProjects()
{
return this.ProjectRepository.GetRaw()
.Include(x => x.Leader)
.Include(x => x.Users)
.Include(x => x.Firm);
}
Usage would look like this then:
var result = GetProjects().Where(x => x.ID == 0).FirstOrDefaultAsync();
Upvotes: 2
Reputation: 14640
You can create the expression as parameter and return it as IQueryable<T>
so it can be continued by another query.
public IQueryable<Project> GetProjects(Expression<Func<Project, bool> query)
{
return this.ProjectRepository.GetRaw()
.Include(x => x.Leader)
.Include(x => x.Users)
.Include(x => x.Firm)
.Where(query);
}
Usage.
var project = await GetProjects(x => x.ID == 0).FirstOrDefaultAsync();
Upvotes: 1