0

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; }
}
CapIsland
  • 129
  • 1
  • 9
  • possible duplicate of ['object' does not contain a definition for 'X'](http://stackoverflow.com/questions/7652749/object-does-not-contain-a-definition-for-x) – Venkata Krishna Mar 18 '15 at 20:15
  • 3
    You should definitely use a model (a view model, specifically) rather than ViewBag. You should avoid using ViewBag as much as possible. – mason Mar 18 '15 at 20:15
  • 2
    _Anonymous objects are emitted as internal by the compiler. The Razor views are automatically compiled into a separate assembly by the ASP.NET runtime. This means that you cannot access any anonymous objects generated in your controllers._ Define a ViewModel – Venkata Krishna Mar 18 '15 at 20:15
  • Ah, that explains the error. So how do I do this without anonymous objects? Do I have to define a class? – CapIsland Mar 18 '15 at 20:19
  • I was wondering whether to just put the code for the SUM in a partial class adding on to the Account entity, but it means sending in the dbContext and that did not seem elegant. I didn't want to create a whole new class for Account just to contain the SUM. – CapIsland Mar 18 '15 at 20:22
  • Okay, I've sorted it with a model. Thanks for everyone's help. – CapIsland Mar 18 '15 at 21:03

0 Answers0