tags:

views:

68

answers:

4

I want to return the depart number that is not found Employee Table by comparing Department table.

Person Table

ID        name   salary     job              commision  DeptID 
--------------------------------------------------------------
P001      Jon     2000   Manager    NULL    1
P002      Skeet     1000   Salesman   2000    1
P003      James     2340   Developer  NULL    2
P004      greed     4500   Developer  NULL    2
P005      Joel     1330   Salesman   1200    1
P006      Deol     5000   Architect  NULL    2

Department Table

DeptID  DeptName

    1   Management
    2   Software  
    3   ERP

SQL

select DeptId from dept

where deptId not in (select deptid from person)

When i try to execute the below code

LINQ

var qry = from n in context.Persons
          where n.DeptID !=
          (from m in context.Depts select m.DeptId)
           select new { DeptID = n.DeptID };

I receive the following error

Operator '!=' cannot be applied to operands of type 'int?' and 'System.Linq.IQueryable'

+2  A: 

It sounds that your DeptID field in SQL is set to allow nulls. In that case you'd probably want something along the lines of this:

var qry = from n in context.Persons
          where n.DeptID.Value !=
          (from m in context.Depts select m.DeptId)
           select new { DeptID = n.DeptID.Value };
Agent_9191
+3  A: 
var qry = from n in context.Persons
          where n.DeptID !=
          (from m in context.Depts select m.DeptId).FirstOrDefault()
           select new { DeptID = n.DeptID };

You are trying to compare DeptID with a collection 1 or more department Ids. Even if there would only logically be one result for a DeptID, syntactically you need to specify that you want the first hit.

ifwdev
This question will however not do what the OP has requested, it will take the first row from the Depts table, and return all the deptsIDs from the row Persons that differ from that first one. The tables should be exchanged in the question.
Jonatan Lindén
Good observation. I was more focused on the exception than the question.
ifwdev
+2  A: 

Suggested rephrasing:

var q = from m in context.Depts
        where
        !context.Persons.Select(p => p.DeptID).Contains(m.DeptID)
        select new { DeptID = m.DeptID };
Jonatan Lindén
+1  A: 

I think it should be something like that. I tried to get a list of DeptID's first and then implement a NOT IN with contains :

var deptIDs = context.Persons
     .Where( p => !context.Depts
             .Select(d => new {DeptID = d.DeptID})
             .Contains( p.DeptID ) 
            )
     .Select( p => new { DeptID = n.DeptID } );
Canavar