I am trying to do queries towards a SQL server and turn the results into models I've designed based on how I want the result to be translated to JSON data for my API.
This is my JSON Models that I am trying create and populate with data
public class JsonProject
{
public int ProjectId { get; set; }
public int ProjectName { get; set; }
public List<JsonJob> Jobs { get; set; }
}
public class JsonJob
{
public int JobId { get; set; }
public int JobName { get; set; }
public List<JsonResource> Resources { get; set; }
}
public class JsonResource
{
public int ResourceId { get; set; }
public DateTime DateStart { get; set; }
public DateTime DateEnd { get; set; }
}
This is my method for making the query which return data to the controller
//Param in is "resourceId"
var query = from rb in db.ResourceBooking
join rrb in db.ResourceRoleBooking on rb.IdResourceBooking equals rrb.IdResourceBooking
join job in db.Job on rrb.IdJob equals job.IdJob
join project in db.Project on job.IdProject equals project.IdProject
where rb.IdAddress == resourceId //all resources is stored as an address
orderby rrb.DateStart
group new {
rb,
rrb,
job,
project
} by new {
ProjectId = project.IdProject,
ProjectName = project.Name
} into g
select new JsonProject {
ProjectId = g.Key.ProjectId,
ProjectName = g.Key.ProjectName,
Jobs = g.Select( x => new JsonJob { // The Problem
JobId = x.job.Id,
JobName = x.job.Name,
Resources = null // null for now until I get JsonJob working
}).ToList()
};
A Job belongs to a Project, a Job has resources booked first as Role in ResourceRoleBooking, then these roles are linked to specific resources(humans) in ResourceBooking which is where I can search for the users Id.
The query is used when a user wants to see projects he is scheduled to do. The order of the joins is based on placing the WHERE clause at the top of the joins, which I believe will help on performance(?)
I try to group together the data, first for each project. When I try to create new JsonJobs within JsonProjects I run into trouble.
When I try to run this code, it results in a InvalidOperationException
)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.
-To troubleshoot I tried turning the JsonProject.Jobs into an integer and using Jobs = g.Sum(x => x.job.Id)
which worked. I could then see how projects with multiple jobs had a higher number.
-If I try to use anonymous types (select new { ProjectId = g.Key.ProjectId, JobId = g.Select(x => new { JobName = x.job.Name }).ToList()
it returns no results.