Search code examples
c#lambdaasp.net-mvc-4asp.net-mvc-viewmodel

Expert opinion on lambda expressions - ViewModels


I'm fairly new to ASP.NET MVC and to lambda expressions, so I'm trying to figure out the best way to do this.

The situation: Clients have support tickets. I have a ViewModel that I just want to show the number of open tickets and closed tickets.

Is there a better way to handle this? I know that seems general but just want an experts opinion.

TicketStatus completeStatus = _db.TicketStatuses.Single(s => s.Status == "Complete");
DashboardSupportView supportView = new DashboardSupportView();

supportView.OpenTickets = _db.Tickets
 .Where(t => t.ClientID == client.ClientID)
 .Where(n => n.TicketStatus.TicketStatusID != completeStatus.TicketStatusID)
 .Count();

supportView.ClosedTickets = _db.Tickets
 .Where(t => t.ClientID == client.ClientID)
 .Where(t => t.TicketStatus.TicketStatusID == completeStatus.TicketStatusID)
 .Count();
return PartialView(supportView)

Solution

  • Yes, it is ok. I recommend you change it a little:

    TicketStatus completeStatus = _db.TicketStatuses.Single(s => s.Status == "Complete");
    DashboardSupportView supportView = new DashboardSupportView();
    supportView.OpenTickets = _db.Tickets.Count(t => t.ClientID == client.ClientID && t.TicketStatus.TicketStatusID != completeStatus.TicketStatusID);
    supportView.ClosedTickets = _db.Tickets.Count(t => t.ClientID == client.ClientID &&  t.TicketStatus.TicketStatusID == completeStatus.TicketStatusID);
    return PartialView(supportView)
    

    Or, it your client entity has a navigation property, you could do it as follow:

    TicketStatus completeStatus = _db.TicketStatuses.Single(s => s.Status == "Complete");
    Client entityClient = _db.Clients.Single(c => c.ClientID == client.ClientID);
    DashboardSupportView supportView = new DashboardSupportView();
    supportView.OpenTickets = entityClient.Tickets.Count(t.TicketStatus.TicketStatusID != completeStatus.TicketStatusID);
    supportView.ClosedTickets = entityClient.Tickets.Count(t.TicketStatus.TicketStatusID == completeStatus.TicketStatusID);
    return PartialView(supportView)