49

I have written this code

IQueryable<Site> sites = context.MainTable.Include("RelatedTable");

if (!string.IsNullOrEmpty(param1)) {
    sites = sites.Where(s => s.RelatedTable != null && s.RelatedTable.Any(p => p.Name == param1.ToLower() && p.PolicyType == "primary"));
}

foreach (string secondaryPolicy in secondaryPolicies)
{
    sites = sites.Where(s => s.RelatedTable != null && s.RelatedTable.Any(p => p.Name == secondaryPolicy.ToLower() && p.PolicyType == "secondary"));
}

return sites.ToList();

However at the ToList line I am getting the exception

Cannot compare elements of type 'System.Collections.Generic.ICollection`1[[Project1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]'. Only primitive types, enumeration types and entity types are supported.

7 Answers 7

81

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 => p.Name == 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.

6
  • I removed the null check and the code threw a Object Not set to Reference Exception. Commented May 29, 2014 at 15:58
  • Strange. As an IQueryable, that shouldn't occur if you are using entities. Anyway, does it work if you keep it in there?
    – Nathan A
    Commented May 29, 2014 at 16:00
  • 1
    You are correct. I had some other mistake in my code. Commented May 29, 2014 at 19:11
  • 3
    I don't get, RelatedTable is a list, how can there be any RelatedTableId? mine doesn't have this.
    – Elaine
    Commented Jul 20, 2016 at 10:09
  • I was using sRelatedTable.Where(p => p.Name == param1.ToLower()).Any() I changed it for your solutions and now is working Thanks! Commented May 31, 2017 at 4:50
15

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

2
  • So strange and simple
    – Guy Biber
    Commented Mar 6, 2020 at 15:58
  • 3
    This isn't right at all. Null checks get used all the time in where clauses. It's a null check against an ICollection that represents an Included tables that is the issue...
    – Isaac
    Commented Sep 24, 2020 at 4:49
15

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

Incorrect

dbContext.MainTable.Where(c => c.RelatedTable==null )

Correct

dbContext.MainTable.Where(c => !c.RelatedTable.Any() )
1
  • still not perfect, especially in case where object (mainTable) has null reference for nested child (relatedTable), this solution ends up with exception as Any() dont compares with null. Solution from @Nathan A looks more correct from business logic point of view.
    – st35ly
    Commented Apr 18, 2017 at 1:23
5

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=1.0.0.0, 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; }
1

I also have the same situation. It then passed by comparing null with FirstOrDefault(). In your case, I applied as per below

    sites = sites.Where(s => s.RelatedTable.FirstOrDefault() != null && s.RelatedTable.Any(p => p.Name == param1.ToLower() && p.PolicyType == "primary"));
0

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 s.Id equals r.Id
               select s; 

  return result;

1 to many

  var result = from s in context.Sites
               join r in context.RelatedTable on s.Id equals r.Site.Id
               into rs
               where rs.RelatedTable.Any(p => p.Name == param1.ToLower() && p.PolicyType == "primary")
               select s
-1

It work me , I just remove the null check;

correct: result=

db.EmpTable.FirstOrDefault().ProjectsAssign.Name,

InCorrect : result=

db.EmpTable!=null && db.EmpTable.FirstOrDefault().ProjectsAssign!=null ? 
      db.EmpTable.FirstOrDefault().ProjectsAssign.Name : null,

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.