-1

I have two tables.

1) Employee which have Id, Name, DeptId columns.

2) Department which have Id and DeptName columns.

I want to find all department which have no any employee using Linq to sql.

IN sql I use below query:

Select * from Department Where Id not in 
(Select DeptId from Employee where DeptId Is not Null )
NightOwl888
  • 55,572
  • 24
  • 139
  • 212
Hitesh
  • 1,188
  • 5
  • 30
  • 52

3 Answers3

1

I hope this will work for you.

var empWithDepartments = from emp in Employee where emp.DeptId != NULL select emp.DeptId;
var result = from dep in Department where !empWithDepartments.Contains(dep.Id) select dep;
trinadh
  • 258
  • 4
  • 14
1

You can do this using LINQ left join like this:-

var result = from d in departments
             join e in employees
             on d.Id equals e.DeptId into es
             from x in es.DefaultIfEmpty()
             where x == null
             select new Department { Id = d.Id, Name = d.Name};

Check this Fiddle for example with some custom objects.

In SQL this is equivalent to:-

SELECT D.*
FROM Department D
LEFT JOIN Employee E
   ON D.Id = E.DeptId
WHERE E.id IS NULL
Rahul Singh
  • 21,585
  • 6
  • 41
  • 56
1

Try this:

var query = from d in Departments
 where !(from e in Employees select e.FkDepartmentId).Contains(d.DepartmentId)
select d;

According to this post this would work with LINQ-TO-SQL but not with LINQ-TO-EF.

devC
  • 1,384
  • 5
  • 32
  • 56