I am trying to find how to do this, and here is what I get:
int[] langIds = new int[] { 1, 3, 5 }; var lang = _context.Languages.Where(x => langIds.Contains(x.id)); var result = _context.Students.Where(x => !lang .Except(x.StudentLanguages .Select(y => y.Language) .Intersect(lang)).Any());
Here I use the Except and Intersect linqToSQL extension methods.
It produces this SQL statement:
SELECT [t0].[id], [t0].[name] FROM [dbo].[Student] AS [t0] WHERE NOT (EXISTS( SELECT NULL AS [EMPTY] FROM ( SELECT DISTINCT [t1].[id], [t1].[name] FROM [dbo].[Language] AS [t1] WHERE (NOT (EXISTS( SELECT NULL AS [EMPTY] FROM ( SELECT DISTINCT [t3].[id], [t3].[name] FROM [dbo].[StudentLanguage] AS [t2] INNER JOIN [dbo].[Language] AS [t3] ON [t3].[id] = [t2].[langId] WHERE (EXISTS( SELECT NULL AS [EMPTY] FROM [dbo].[Language] AS [t4] WHERE ([t3].[id] = [t4].[id]) AND ([t4].[id] IN (@p0, @p1, @p2)) )) AND ([t2].[studentId] = [t0].[id]) ) AS [t5] WHERE [t1].[id] = [t5].[id] ))) AND ([t1].[id] IN (@p3, @p4, @p5)) ) AS [t6] ))
Please note that I populate the languages ββfrom the database. Unfortunately, you cannot use local collections in your query , since LinqToSQL does not know how to translate them into SQL. If you do the same with a local int array or any other collection, you will get this exception:
LINQ To SQL exception: A local sequence cannot be used in LINQ to SQL implementation of query statements other than the statement Contains
source share