Using Entity framework, I have an Account entity (id, name) and an AccountEntry entity (id, AccountID, Entry).
I want a summary page that shows all the accounts in Account along with their respective balances (sum of Entry for the AccountID). I have tried putting the values into the ViewBag but it just gives me an error when it tries to use it in the view. Is there an elegant way of sending this information to the view?
This is what I tried:
CONTROLLER:
ViewBag.Accounts = db.Accounts.Select(x => new
{
id = x.Id.ToString(),
Account = x.Name,
Balance = db.AccountEntries.AsEnumerable().Where(y => y.AccountID == x.Id).Select(y => y.Amount).DefaultIfEmpty(0).Sum()
}).ToList();
VIEW:
@foreach (var item in ViewBag.Accounts)
{
<tr>
<td>
@item.Account
</td>
<td>
@item.Balance
</td>
<td>
</td>
</tr>
}
But the view gives an error: Additional information: 'object' does not contain a definition for 'Account', even though the debug shows it has the value there.
What's the best practice for this? Do I use a model?
And what is the best practice if I also, in addition to the accounts, want to send in other lists of summary information?
EDITED: Is this a good View Model for the above?
Is this a good View Model?
public class SummaryModel
{
public class AccountSummary
{
public Account account { get; set; }
public decimal Balance { get; set; }
}
public IEnumerable<AccountSummary> AccountSummaries { get; set; }
}