对于ASP.NET MVC和lambda表达式,我还是一个新手,所以我试图找出最佳方法。

情况:客户有支持票。我有一个ViewModel,我只想显示打开票证和关闭票证的数量。

有没有更好的方法来解决这个问题?我知道这似乎很笼统,但只想请专家发表意见。

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)

最佳答案

是的,没关系。我建议您对其进行一些更改:

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)


或者,如果您的客户实体具有导航属性,则可以执行以下操作:

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)

10-07 23:17