0

I am trying to perform a Join of multiple tables in LINQ.

I have the following classes:

public class Project {
    public int Id { get; set; }
    public string Name { get; set; }
}

public class Batch {
    public int Id { get; set; }
    public int ProjectId { get; set; }
    public Decimal Hours { get; set; }
    public Decimal DailyRate { get; set; }
}

public class TimeEntry
{
    public int Id { get; set; }
    public int BatchId { get; set; }
    public Decimal Expense { get; set; }
}

I am joining these Tables with the following LINQ expression, which worked like a charm:

from project in _context.Projects
join batch in _context.Batches on project.Id equals batch.ProjectId into batchGroup from batch in batchGroup.DefaultIfEmpty()
join timeEntry in _context.TimeEntries on batch.Id equals timeEntry.BatchId into timeEntryGroup from timeEntriy in timeEntryGroup.DefaultIfEmpty()
select new {
    project,
    batch,
    timeEntriy
};

But when I try to group the result i get an exception

from project in _context.Projects
join batch in _context.Batches on project.Id equals batch.ProjectId into batchGroup from batch in batchGroup.DefaultIfEmpty()
join timeEntry in _context.TimeEntries on batch.Id equals timeEntry.BatchId into timeEntryGroup from timeEntriy in timeEntryGroup.DefaultIfEmpty()
group  new {
    project,
    batch,
    timeEntriy
} by project.Id into g
select new {
    Id = g.Key,
    Hours = g.Sum(q => (q.batch == null ? 0 : q.batch.Hours))
};

// "Object reference not set to an instance of an object."

Can someone explain me what happens here or what i am missing?

0 Answers0