Korijn
Korijn

Reputation: 1403

How to efficiently select child objects through LINQ

In an effort to access child objects only through their aggregate roots, I am struggling to think of efficient ways to select the correct data. Could I rewrite the following to be more efficient/concise?

        var jobReport = db.Jobs
            .Where(j => j.JobReports.Any(jr => jr.ReportId == reportId))
            .Select(j => j.JobReports.Single(jr => jr.ReportId == reportId))
            .Single();

Upvotes: 0

Views: 62

Answers (1)

decPL
decPL

Reputation: 5402

What you wrote would be equivalent to:

var jobReport = db.Jobs.SelectMany(j => j.JobReports)
                       .Single(jr => jr.ReportId == reportId);

Upvotes: 3

Related Questions