Reputation: 5917
I have the following code:
var statements = db.statement
.OrderByDescending(d => d.id)
.Take(5)
.AsEnumerable()
.Select(d => new Statements
{
Accounts = d.statement_entry.AsEnumerable()
.GroupBy(b => b.currency)
.Select(b =>
new Account
{
In = b.Where(l => l.amount > 0).Sum(l => l.amount),
Out = b.Where(l => l.amount < 0).Sum(l => l.amount),
Balance = b.Sum(l => l.amount),
Currency = b.Key
}).OrderBy(b => b.Currency),
UploadedDate = d.uploaded_date,
Id = d.id
})
.ToList();
Is there a way that I could do it without the AsEnumerable()
? From what I understand the AsEnumberable
will cause a query to take place for each of the statement
s returned.
Or is there a better way to refactor the code?
Upvotes: 0
Views: 348
Reputation: 111820
You understand wrongly. AsEnumerable
will make the query execute on the local (client) machine.
This
statements = db.statement
.OrderByDescending(d => d.id)
.Take(5)
will be executed on the (SQL) server,
the remaining part on the client
Why are you puttin the AsEnumerable
? I think the query should work even without (and it would do everything server-side)
The only thing is that after the OrderBy(b => b.Currency)
you should put a .ToList()
so that the .Select(b => new Account
is materialized and cached.
Upvotes: 1