Accepted answer

you can't compare a related table to null directly. instead, compare against your foreign key member (assuming that primarytable reference relatedtable using a member called relatedtableid.

sites.where(s => s.relatedtableid != null && s.relatedtable.any(
    p => == param1.tolower() && p.policytype == "primary"));

you may even be able to get away with removing the null check completely. since this query is run against the database, you won't get a nullreferenceexception and it may work. you'll have to double check on that though.


it work me , i just remove the null check;

correct: result=


incorrect : result=

db.emptable!=null && db.emptable.firstordefault().projectsassign!=null ? 
      db.emptable.firstordefault() : null,


i don't have a foreign key field configured because the relationship between maintable and relatedtable in my case is 1 to 1. however for a 1 to many relationship if you don't have foreign key but you have a navigation property to the maintable model in the relatedmodel model the following solution also works.

1 to 1

  var result = from s in context.sites
               join r in context.relatedtable on equals
               select s; 

  return result;

1 to many

  var result = from s in context.sites
               join r in context.relatedtable on equals
               into rs
               where rs.relatedtable.any(p => == param1.tolower() && p.policytype == "primary")
               select s


collection field can be null in this case you get exception nullreferenceexception

when use relatedtables.any()

if you add relatedtables != null as in a question then you can get

cannot compare elements of type 'system.collections.generic.icollection`1[[project1, version=, culture=neutral, publickeytoken=null]]'. only primitive types, enumeration types and entity types are supported.

if you get the nullreferenceexception exception, lazy loading is not turned off and you are good with lazy loading for the field then to prevent exception mark field with virtual keyword to allow lazy loading for the field

virtual icollection<table> relatedtables{ get; set; }


the error can occur if navigation collection compared with null. it should be checked if any record exist. in the particular example any is used anyway, so check collection to null is redundant


dbcontext.maintable.where(c => c.relatedtable==null )


dbcontext.maintable.where(c => !c.relatedtable.any() )


it is because that you have a null check in the where clause.

Related Query

More Query from same tag