I am trying to translate the following query into entity framework:
SELECT Subjects.Name
FROM Subjects LEFT OUTER JOIN
Projects_Subjects ON Subjects.ID = Projects_Subjects.Section_ID
WHERE (Projects_Subjects.Project_ID IS NULL) OR
(Projects_Subjects.Project_ID <> 2)
Where subjects is a simple table with subject.ID, subject.Name and Projects_Subjects is a table effecting the many-to-many relationship between subjects and projects, with Projects_Subjects.Project_ID and Projects_Subjects.Subject_ID columns.
This query works fine in SQL, in that it returns all the subjects which are not yet associated with the project with ID = 2.
I am trying to translate this to Linq to Entities. So far I have:
db.Subjects.Where(s => s.Projects == null || !s.Projects.Select(p => p.ID).Contains(ProjectID))
Which the compiler is happy with as far as syntax goes, but at runtime I get the following error:
'System.Data.Objects.DataClasses.EntityCollection`1'. Only primitive types (such as Int32, String, and Guid) and entity types are supported.
There is no other info really. As far as I can tell it doesn’t like the s.Projects == null bit as it works fine if I take that out. Question is: How can I perform that check on the entity collection?
You’re not checking for a column to be null, but for an associated property (another entity) to be null. As you point out, that’s the default state.
That exception that you got basically means that only POCO types can be sent to SQL for comparison in where / order by statements against SQL types. EF thinks you’re trying to compare objects here so complains.