我正在尝试在LINQ中执行多个表的连接。
我有以下课程:
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; }
}
我正在使用以下LINQ表达式加入这些表,这些表达式就像一个魅力:
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
};
但是当我尝试对结果进行分组时,我得到了异常
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."
有人可以解释一下这里发生了什么或我错过了什么?