What would be the linq-2-sql syntax for this SQL Query:

SELECT emp.id, Name, Count(t.id) as CNT 
FROM employee emp 
LEFT JOIN taskAssignment t 
on emp.id = t.FKEmployeeID GROUP BY emp.id, Name

tables are like this: enter image description here

有帮助吗?

解决方案

Here is the answer

var lst = from emp in Employeetables
join task in TaskAssignmentTables
    on  emp.EmployeeId equals task.FKEmployeeId into j 
    from result in j.DefaultIfEmpty()
    group result by new { emp.EmployeeId, emp.Name }  into groupResult
select new
{
    EmployeeId = groupResult.Key.EmployeeId,
    Name = groupResult.Key.Name,
    Count = groupResult.Count(r => r.FKEmployeeId != null)
};

This returns the same answer as your SQL question related to this SQL Left outer join question. I developed this simply using LinqPad

其他提示

Not very sure if this will work but it is definitely worth a try.

If it doesnt work as expected then please let me know what query does it fire on the database so that I can improve accordingly.

List<Employee> employee = new List<Employee>() 
{ 
    new Employee() { id = 1, Name = "Samar" }, 
    new Employee() { id = 1, Name = "Samar" },
    new Employee() { id = 1, Name = "Samar" },
    new Employee() { id = 2, Name = "Sid" }
};

List<TaskAssignment> taskAssignment = new List<TaskAssignment>() 
{ 
    new TaskAssignment(){FKEmployeeID = 1},
    new TaskAssignment(){FKEmployeeID = 1}
};


var cls = from e in employee
            join emp in taskAssignment on e.id equals emp.FKEmployeeID into empout
            group e by new { e.id, e.Name } into g
            select new { g.Key.id, g.Key.Name, CNT = g.Count() };

Hope this helps.

Try this.

var employees = from emp in dbContext.Employees
                    join task in dbContext.TaskAssignmentTable 
                    on emp.employeeID equals task.FKEmployeeID
                    into tEmpWithTask
                    from tEmp in tEmpWithTask.DefaultIfEmpty()
                    group tEmp by new { emp.EmployeeID, emp.Name } into grp
                    select new {
                      grp.Key.EmployeeID,
                      grp.Key.Name,
                      grp.Count(t=>t.TaskID != null)
                    };
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top