dave317
dave317

Reputation: 774

Perform a calculation in MVC viewmodel

Trying to perform a calculation in a view model. I have two donation columns, want to add them together in the viewmodel.

This is in the ViewModel Class:

[DataType(DataType.Currency)]
public decimal ttlDonation
{
  get { return Donation.GetValueOrDefault() + GuestDonation.GetValueOrDefault(); }
}

The Viewmodel builds fine, and it displays properly in the razor view using (modelItem => item.ttlDonation). Problem is when I try to SUM this expression with a LINQ query in the controller like so:

var DonateTTl = GuestViewModel.Sum(f => f.ttlDonation);

Then my code throws an error:

The specified type member 'ttlDonation' is not supported in LINQ to Entities...

I am wondering the best way to do this. I also tried this in my controller (below), where I've changed my viewmodel slightly to a basic get; set; and it still isn't working. What is the best way to do this? Should I perform the calculation on my original Model rather than my viewmodel?

var GuestViewModel = guests.Select(g => new GuestIndexViewData
{
  ID = g.ID,
  FRID = g.FRID,
  FirstName = g.FirstName,
  LastName = g.LastName,
  Company = g.Company,
  email = g.email,
  Donation = g.Donation,
  GuestFirstName = g.GuestFirstName,
  GuestLastName = g.GuestLastName,
  GuestCompany = g.GuestCompany,
  Guestemail = g.Guestemail,
  GuestDonation = g.Donation,
  Attended = g.Attended,
  RSVP = g.RSVP,
  Guest3 = g.Guest3,
  ttlDonation = (g.GuestDonation.GetValueOrDefault() + g.Donation.GetValueOrDefault())
}).OrderBy(f => f.FRID);

var DonateTTl = GuestViewModel.Sum(f => f.ttlDonation);

I know I can find a way to do this but I am looking for the best way to do this as for standards/performance.

Upvotes: 1

Views: 908

Answers (1)

beautifulcoder
beautifulcoder

Reputation: 11320

I think picking it out will work:

var DonateTTl = GuestViewModel.Select(vm => vm.ttlDonation).Sum();

Upvotes: 1

Related Questions