Entity Framework query with "not in"

1.2k views Asked by At

I have a simple (well easy, not simple) query of "not in" on related tables.

SELECT CompetencyID, CompetencyName FROM Competency
WHERE (Deleted = 0) AND (CompanyID = 1) AND (CompetencyID NOT IN(SELECT CompetencyID
FROM CompetencyGroups WHERE (Deleted = 0) AND (CompanyID = 1) AND (GroupID = 1))) AND
(ParentID = 0) ORDER BY CompetencyName

In SQL I get the list that I need with remaining items not in the group. Now I want to bind this to a DataGrid using EF5.

I cannot get the query syntax properly (Using VB.net) to list the ID and the Name of the Competency...

Converted the provided c# answer to VB:

Dim excludeList = context.CompetencyGroups.Where(Function(x) x.Deleted = False And x.GroupID = GroupID).Select(Function(x) x.CompetencyID).ToArray
Dim results = context.Competencies.Where(Function(c) Not excludeList.Contains(c.CompetencyID) And c.Deleted = False And c.CompanyID = 1 And c.ParentID = 0).OrderBy(Function(c) c.CompetencyName)
GridView2.DataSource = results
GridView2.DataBind()

Hope this helps someone in the future. Took me about 4 hours to search, ask and convert...

2

There are 2 answers

1
Greg Ennis On BEST ANSWER

Something like

var excludeList = context.CompetencyGroups.Where(x => x....).Select(x => x.CompetencyID).ToArray();
var results = context.Competency.Where(x => !excludeList.Contains(x.CompetencyID));

Update: Somebody else edited this and then someone rejected it, but the edit was a good one (to select the value)

0
OneFineDay On

If you need the Cast to make an array of Integers.

Dim excludeList = context.CompetencyGroups.Cast(Of CompentencyGroup).Select(Function(x) x.CompetencyID).ToArray()
Dim results = context.Competency.Where(Function(x) Not excludeList.Contains(x.CompetencyID))