【问题标题】:LINQ Query for getting count in ASP.Net MVC 5 Application用于获取 ASP.Net MVC 5 应用程序中的计数的 LINQ 查询
【发布时间】:2017-12-28 08:28:04
【问题描述】:

在编写 LINQ 查询以获取基于部门的员工数量时需要帮助。

部门模型

public class Department
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Employee> Employees { get; set; }
}

员工模型

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int DepartmentId { get; set; }
    public Department Department { get; set; }
}

MyViewModel

public class MyViewModel
{
    public string Department { get; set; }
    public int count { get; set; }
}

LINQ 查询

    public ActionResult shows()
    {
        //one department can have many employees and one employee can only be parrt of one department
        // below LINQ query fetches the count of employees belonging to each department
        var x = _context.Employees.Include("Department").GroupBy(e => e.DepartmentId)
     .Select(y=> new MyViewModel{
             Department= y.Key, // ERROR HERE AS Cannot type cast string to integer
            count = y.Count()               
        }).ToList();
     // code removed for brevity
        return Content("x");
    }

预期输出

Department                 Count (or employees)

Human Resource               10

Information Tech              5

问题 如何编写 LINQ 查询以获取上述输出。请指导我。

【问题讨论】:

  • Department= y.First().Department.Name,(假设Department包含一个名为Name的属性)
  • @StephenMuecke:我真的很抱歉,但我没能关注你。在本教程中,“youtube.com/…”在 1:57 分钟对导师来说工作正常。
  • Department= y.Key 更改为 Department= y.First().Department.Name
  • 该教程使用GroupBy(e =&gt; e.Department.Name),在这种情况下您可以使用Department= y.Key,
  • 我收到了the "first" cannot be used a final query operation"的错误

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


【解决方案1】:

您有 2 个选项可用于修改查询。我假设您的 Department 模型包含一个属性 string Name,您希望将其分配给您的视图模型的 Department 属性。

  1. 获取分组集合中的第一个 Department 并分配其 Name 属性到您的视图模型 Department 属性。注意 您需要在 .GroupBy() 之前添加 .ToList() 以便 查询的第一部分在分组之前执行

    var x = _context.Employees
        .Include("Department")
        .ToList()
        .GroupBy(e => e.DepartmentId)
        .Select(y => new MyViewModel
        {
             Department = y.First().Department.Name,
             count = y.Count()               
        }).ToList();
    
  2. .GroupBy() 表达式更改为按Name 属性分组 Department 的属性

    var x = _context.Employees
        .Include("Department")
        .GroupBy(e => e.Department.Name)
        .Select(y=> new MyViewModel
        {
            Department = y.Key,
            count = y.Count()               
        }).ToList();
    

【讨论】:

  • 请解释为什么即使按 ID 分组(逻辑错误)我们仍然得到正确的输出。
  • 警告这里仅按部门的名称属性进行分组只有在您对名称列具有唯一约束以确保您具有唯一的部门名称时才能正常工作。如果由于某种原因您有重复的部门名称,您将获得这些部门的员工总数,比如说两个部门。最好的办法是按 Id AND Name 分组,请参阅我的回答。
  • @MihailShishkov:非常有道理。我只是为了学习目的而这样做,但我会注意你所说的。万分感谢!。我也会尝试你的解决方案。 :)
  • @MihailShishkov,您的回答是按员工 DepartmentId 和员工 Name(不是部门 Name)分组,这不是 OP 想要的
  • 在选项 1 中,您必须从数据库中检索每个员工,这很糟糕。如果有成千上万的员工怎么办?实际上,您需要@Unbreakable 是在服务器上执行此 SQL SELECT DepId, Name, COUNT(1) AS EmplCount FROM Employees GROUP BY DepId, Name
【解决方案2】:
public ActionResult shows()
    {
        //one department can have many employees and one employee can only be parrt of one department
        // below LINQ query fetches the count of employees belonging to each department
        var x = _context.Employees.Include("Department").GroupBy(e => new { e.DepartmentId, e.Department.Name})
     .Select(y=> new MyViewModel{
             Department= y.Key.Name
            count = y.Count()               
        }).ToList();
     // code removed for brevity
        return Content("x");
    }

这里的关键是按 DepartmentId AND Name 分组

【讨论】:

    【解决方案3】:

    试试这样:

    public ActionResult shows()
    {
        //one department can have many employees and one employee can only be parrt of one department
        // below LINQ query fetches the count of employees belonging to each department
        var x = _context.Employees.Include("Department").GroupBy(e => e.DepartmentId)
     .Select(y=> new MyViewModel{
             Department= y.Key.DepartmentName, // or whatever property you have for storing the name
            count = y.Count()               
        }).ToList();
     // code removed for brevity
        return Content("x");
    }
    

    【讨论】:

      【解决方案4】:

      您可以使用此代码:

      using System.Linq;
      using System.Web.Mvc;
      using MvcApplication1.Models;
      
      namespace MvcApplication1.Controllers
      {
           
           public class HomeController : Controller
           {
                public ActionResult Index()
                {
                     var dataContext = new MovieDataContext();
                     int count = (from row in dataContext.Movies
                          where row.IsEnquiry == true
                       select row).Count();
                     ViewBag.ItemCount = count;
                     return View();
                }
           }
      }
      

      【讨论】:

      • 解释你的答案
      猜你喜欢
      • 2017-09-24
      • 1970-01-01
      • 1970-01-01
      • 2016-04-06
      • 1970-01-01
      • 2013-11-30
      • 1970-01-01
      • 2016-11-10
      • 2020-10-16
      相关资源
      最近更新 更多