如何在Silverlight中的一个linq查询中查询和计算Employees表和Project表?

时间:2009-05-29 19:41:21

标签: linq silverlight datagrid

我有两个表,一个员工表和一个项目表,我希望带回一个分配给每个项目的员工数量。在employee表中我有employeeIDs和projectIDs,在项目表中我有projectID,名称,部门,笔记等。我希望带回以下信息并在Silverlight中的一个DataGrid中显示它与员工人数以计数的形式分配给每个项目。

名称部门备注计数

2 个答案:

答案 0 :(得分:3)

有很多方法可以做到这一点,但最简单的方法可能是这样做:

var x =
    from proj in db.Projects
    select new
    {
        Name = proj.Name,
        Department = proj.Department,
        Notes = proj.Notes,
        Count = db.Employees.Where(emp => emp.ProjectID == proj.ProjectID).Count()
    };

或者,如果你在ProjectID上的Projects和Employees之间创建了一个外键(如果没有,你应该强烈考虑这样做),LINQ将提供更清晰的语法:

var x =
    from proj in db.Projects
    select new
    {
        Name = proj.Name,
        Department = proj.Department,
        Notes = proj.Notes,
        Count = proj.Employees.Count()
    };

它没有比这更好!

答案 1 :(得分:1)

我想你想要这样的东西......

dbContext dbCon = new dbContext();
            var projects = from project in dbCon.Projects
                           join employee in dbCon.Employees on project.ProjectID equals employee.projectid
                           group employee by new { employee.projectid, project.Name, project.Department, project.Notes } into grouping
                           select new { 
                               //projectID = grouping.Key.projectid, 
                               projectName = grouping.Key.Name,
                               projectDepartment = grouping.Key.Department, 
                               projectNotes = grouping.Key.Notes, 
                               count = grouping.Count() 
                           };