Entity Framework Using a Where Clause on a Nested Entity

c# entity-framework entity-framework-6

Question

I'm trying to filter child objects on the retrieval using the following

var loanExtractExample = be.LoanCategoryMonitors
                .Where(lcm => lcm.LoanNumber == 5000435)
                .Include(l => l.Loan)
                .Include(le => le.LoanExtracts)
                .Select(le => le.LoanExtracts.Borrowers.Where(b => b.BorrowerNum == 1))
                .ToList();

but when I check the entity collection there are 2 borrowers. One with BorrowerNum 1 and one with BorrowerNum = 3.

What am I missing to be able to reduce the borrowers to the correct one?

1
4
6/7/2018 3:10:28 AM

Popular Answer

The Select for the borrowers I believe would returning the borrowers for loan category monitors where a monitor had a borrower with ID 1. I believe what you are looking for is:

var matchingBorrowers = be.LoanCategoryMonitors
                .Where(lcm => lcm.LoanNumber == 5000435)
                .SelectMany(le => le.LoanExtracts.Borrowers) // Borrowers for loan extracts against loan 5000435...
                .Where(b => b.BorrowerNum == 1)) // Of those borrowers, those with BorrowerNum = 1.
                .ToList();

Includes aren't needed since you're not retrieving a loan category monitor, but you might want to add any .Include() statements for child references of the borrowers that are returned. (after the .SelectMany())

0
6/7/2018 8:15:45 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow