Need help with LINQ query and ASP.NET MVC?
-
10-07-2019 - |
Question
My repository returns a list of Accounts.
Each account has a date and a MoneySpent decimal amount. So, I have my list of Accounts and in my controller I'm trying to process this list a little.
I want to have an object which contains the string name of all the months in my Account list and a Sum of all money spent for that month.
Here is what I have tried:
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Detail(int id)
{
var recentAccounts = accountRepository.GetAccountsSince(DateTime.Now.AddMonths(-6));
var monthlyTotals = from a in recentAccounts
group a by a.DateAssigned.Month.ToString("MMM") into m
select new
{
Month = m.Key,
MonthSum = m.Sum(a => a.MoneySpent)
};
return View();
}
Does this seem like the right way to calculate monthlyTotals?
Also, I've been using strongly typed views with ViewModels for each view, so what type should I make monthlyTotals so I can add it as a field on my ViewModel and pass it to my View?
Solution
Looks right to me.
When I need to pass data like this to my view, I create a class for it. So your class would look like this:
public class MonthlyTotal
{
public string Month { get; set; }
public decimal MonthSum { get; set; }
}
and your SELECT clause would look like this:
select new MonthlyTotal
{
Month = m.Key,
MonthSum= m.Sum(a => a.AmountAssigned)
}
OTHER TIPS
I would probably break out that logic into a service layer class holding business logic. Along with that, if the view is expecting a structure different than the model, you would transform your results in your service method returning a custom model type.
Using an anonymous type won't work since the view code won't know what properties it has. I suggest creating a view-only model in the Models directory.
public class MonthlySumModel
{
public string Month { get; set; }
public decimal Sum { get; set; }
}
Then create a new model value in the select statement:
select new MonthlySumModel
{
Month = m.Key,
Sum = m.Sum(a => a.MoneySpent)
};
You can then use this model as the type for the view.