I have two tables, Tasks and TaskMilestones. I want a query to return the most recent past milestone and the nearest future TaskMilestone for each Task. I'm working with C#/LINQ-to-SQL. How do I go about this?
Task columns: Id, TaskName TaskMilestones columns: Id, TaskId, MilestoneName, MilestoneDate
I want a return table with rows containing: TaskName, MilestoneDate, MilestoneName
My current solution causes Linq to query the database once for each Task, which is unacceptably slow.
[EDIT to address comments] The current implementation is simple and not a single statement, it just queries the list of Tasks and then queries for each TaskId twice with proper where clauses:
var x = from p in this.Database.Task
join pm in this.Database.TaskMilestones on p.Id equals pm.TaskId
select new
{
TaskId = p.Id,
TaskName = p.Name,
MilestoneName = m.Name,
MilestoneDate = pm.MilestoneDate,
};
foreach (var record in records)
{
var y = x.Where(p => p.TaskId == record.Id && p.MilestoneDate <= dt);
var z = x.Where(p => p.TaskId == record.Id && p.MilestoneDate > dt);
...