分组在mvc5中查询

时间:2016-10-25 11:35:46

标签: c# sql-server linq asp.net-mvc-5

您好我想在我的MVC5应用程序的C#中通过查询编写sql Group。

Groupby query in sql

在上面的图像中,我通过查询分组,我在sql中编写。我想用C#前端编写。

C# Code

我试图在前端编写查询。但是我收到了图片中提到的错误。现在我想在C#中编写Group By查询,并希望显示每个员工的计数(输出与第一个图像中提到的相同)。任何人都可以帮我解决这个问题吗?

我的ViewModel(Dashnboard View模型)

public class DashboardViewmodel
{
    public List<CustomerTypeCountModel> CustomerTypesCountModels { get; set; }
    public List<View_VisitorsForm> Visits { get; set; }
    public CustomerTypeViewModel CustomerTypeViewModels { get; set; }
    public int sizingcount { get; set; }
    public int Processingcount { get; set; }

    //here i declared two properties
    public string EmployeeName { get; set; }
    public string EmployeeCount { get; set; }
}

我的控制器代码

[HttpGet]
public ActionResult SalesVisit()
{
    return View();
}

public ActionResult GetDatesFromSalesVisit(DashboardViewmodel dvm)
{
    var fromdate = Convert.ToDateTime(dvm.CustomerTypeViewModels.FromDate);
    var todate = Convert.ToDateTime(dvm.CustomerTypeViewModels.ToDate);

    List<View_VisitorsForm> empcount = new List<View_VisitorsForm>();

   if (DepartmentID == new Guid("47D2C992-1CB6-44AA-91CA-6AA3C338447E") &&
      (UserTypeID == new Guid("106D02CC-7DC2-42BF-AC6F-D683ADDC1824") ||
      (UserTypeID == new Guid("B3728982-0016-4562-BF73-E9B8B99BD501"))))

       {

    var empcountresult = db.View_VisitorsForm.GroupBy(G => G.Employee)
                          .Select(e => new
                          {
                              employee = e.Key,
                              count = e.Count()
                          }).ToList();

        empcount = empcountresult ;//this line i am getting error 
 }
   DashboardViewmodel obj = new DashboardViewmodel();

     return View("SalesVisit", obj);
}

2 个答案:

答案 0 :(得分:4)

当您使用GroupBy时,您会获得IEnumerable<IGrouping<Key,YourOriginalType>>,因此您没有.Employee.VisitingID属性。

更改如下:

public class EmployeeCount
{
    public string Employee {get; set;}
    public int Count {get; set;}
}

List<EmployeeCount> result = db.View_VisitorsForm
               .Where(item => item.VisitingDate >= beginDate && item.VisitingDate < endDate)
               .GroupBy(G => G.Employee)
               .Select(e =>new EmployeeCount
               {
                   employee = e.Key,
                   count = e.Count()
               }).ToList();

//Now add the result to the object you are passing to the View

还要记住,您没有实例化View_VisitorsForm类型的对象,而是实例化匿名对象,因此将结果分配给empcount但仅使用添加的FirstOrDefault将无法编译

要将此结构传递给视图并显示它,请选中this question

答案 1 :(得分:-1)

希望这可以帮助你

 var query = db.View_VisitorsForm.Where(o => o.VisitingDate >= new DateTime(2016,10,01) && o.VisitingDate <= new DateTime(2016, 10, 30)).GroupBy(G => G.Employee)

foreach (var item in query)
                {
                    Console.WriteLine($"Employee Id {item.Key} : Count :{item.Count()}");
                }