开发者

Entity framework equivalent to SQL 'IS NULL'

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?


The answer is that I am an idiot. The default for a linq to entity query is that it will return everything and you just need to subtract from there. So simply

db.Subjects.Where(s => !s.Projects.Select(p => p.ID).Contains(ProjectID))

Actually does what I wanted it to do... Sorry for the waste of time.


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.


Something like this?

var subjects = from subject in dc.GetTable<Subjects>()
                               join entityProjects_Subjects in dc.GetTable<Projects_Subjects>()
                                    on subject.ID equals entityProjects_Subjects.Section_ID into tempProjects_Subjects
                               from projects_subjects in tempProjects_Subjects.DefaultIfEmpty()
                               where projects_subjects.Project_ID != 2 || projects_subjects == null
                               select new
                               {                                   
                                   Name = subject.Name
                               };
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜