Linq GroupBy With Passed Where Predicate

时间:2015-03-14 23:33:55

标签: c# linq entity-framework

这很好。g.Key不为空并且有适当的数据:

var result = db.JournalEntries.Include(je => je.JournalRecords.Select(jr => jr.Account).Select(j => j.AccountParticulars))
                .Where(je => je.Date >= existingLedgerTransaction.From && je.Date <= existingLedgerTransaction.To)
                .SelectMany(s => s.JournalRecords)
                .GroupBy(d => d.AccountParticular.Account.AccountCategory)
                .Select(g => new { Name = g.Key.Name });

但是这不起作用,因为g.Key为null:

var DateFilter = new Func<JournalEntry, bool>(je => je.Date >= existingLedgerTransaction.From && je.Date <= existingLedgerTransaction.To);

var result = db.JournalEntries.Include(je => je.JournalRecords.Select(jr => jr.Account).Select(j => j.AccountParticulars))
                .Where(DateFilter)
                .SelectMany(s => s.JournalRecords)
                .GroupBy(d => d.AccountParticular.Account.AccountCategory)
                .Select(g => new { Name = g.Key.Name });

我在一个带有静态集合的简单控制台应用程序中尝试了同样的事情,并且传入谓词工作正常。这可能是什么问题?

注意:禁用延迟加载/动态代理

1 个答案:

答案 0 :(得分:3)

尝试

 var DateFilter = new Expression<Func<JournalEntry, bool>>(je => je.Date >= existingLedgerTransaction.From && je.Date <= existingLedgerTransaction.To);

因为您需要将表达式树传递给EF