Reputation: 81
My goal is to order some data coming back. I love lambda expressions, but they are failing me. The code below gets a wonderful error about not putting a lambda in an include.
public async Task<Header> GetHeader(int HeaderId)
{
var header = await _context.Headers
.Include(location => location.HeaderLocation)
.Include(details => details.Details.OrderBy(x => x.FieldName).OrderBy(y => y.LineVersion).ToList())
.Where(p => p.HeaderId == HeaderId).FirstOrDefaultAsync();
return header;
}
The header has details, and the details need to be ordered by the property "FieldName", then by the property "LineVersion". Error I get:
Lambda expression used inside Include is not valid.
After some digging, I found a couple of ways to get around the lambda, but I am not having any luck with getting an example that has OrderBy, and my brain is failing me at the moment, and would love to get a little kick to get this working.
BTW: the code works fine when it is without the OrderBy, except that the details may not always come back in the order I need them.
Thanks in advance for the help Brad
Upvotes: 2
Views: 7793
Reputation: 81
On top of the other suggestion I have seen, I used the link in the comments of the original post, and got a great answer there, too. I tested it, and it works like a charm. Here is what I ended up with:
public async Task<PermitHeader> GetPermit(int HeaderId)
{
var header = await _context.Headers
.Include(location => location.Location)
.Where(p => p.HeaderId == HeaderId).FirstOrDefaultAsync();
var details = await _context.Details
.OrderBy(ob => ob.FieldName)
.OrderBy(ob => ob.LineVersion)
.Where(d => d.HeaderHeaderId == HeaderId).ToListAsync();
header.Details = Details;
return header;
}
Thanks for a quick response!
Upvotes: 2
Reputation: 5118
I'd use a Select
to get the entities with OrderBy after the Where
but before FirstOrDefaultAsync()
. Like this:
var header = await _context.Headers
.Include(location => location.HeaderLocation)
.Include(details => details.Details)
.Where(p => p.HeaderId == HeaderId)
.Select(header => new Header
{
// Assign Header values
Location = header.Location,
Details = header.Details.OrderBy(h => h.FieldName).OrderBy(h => h.LineVersion)
}).FirstOrDefaultAsync();
Upvotes: 0