23

I have a table named UserTenders having many-to-one relationship with aspnet_Membership table.
I am using EntityFramework 4.0 and when I try something like this, it errors.

var tenders = ctx.UserTenders
    .Where(tender => tender.HasAdminApproved.Equals(true))
    .ToList();

The error is

System.NotSupportedException
Unable to create a constant value of type 'System.Object'.
Only primitive types ('such as Int32, String, and Guid') are supported in this context.

This snippet below works.

var tenders = ctx.UserTenders.ToList();

What could be wrong in my code? Feel like I am missing something very trivial.

I would like to filter all those rows that have the bit field HasAdminApproved as true

naveen
  • 53,448
  • 46
  • 161
  • 251

4 Answers4

39

Try replacing

.Where(tender => tender.HasAdminApproved.Equals(true))

With:

.Where(tender => tender.HasAdminApproved == true)

Or as previously suggested by @Ladislav Mrnka if your field is bool?

.Where(tender => tender.HasAdminApproved)
naveen
  • 53,448
  • 46
  • 161
  • 251
Nick Heidke
  • 2,787
  • 2
  • 34
  • 58
22

@Ladislav told you the correct answer (.Where(tender => tender.HasAdminApproved)), but you might wonder why you get this message.

You're trying to call System.Boolean.Equals(Object obj). So you're boxing the constant true. And L2E, as the message says, has no support for a const of a non-primitive type like System.Object. Hence the error.

Craig Stuntz
  • 125,891
  • 12
  • 252
  • 273
  • 1
    This is the obvious explanation, but why the compiler picks the overload that takes Object while there's an overload that takes Boolean? – Ashraf Sabry Aug 14 '14 at 07:22
  • 1
    @AshrafSabry I'd guess it's not the compiler which picks that overload, it's how EF6 build the query by inspecting lambda expressions, I believe they could have handled this to behave as you suggested, then it would work. Also, since this is not an answer, but just the explanation of the answer, this should be added to the accepted answer using **edit**, or added as a comment, in my opinion (but ok, since this is very old). – Alisson Reinaldo Silva Jun 29 '17 at 17:27
7

I had the same exception caused by a different problem: a char versus a string used as a constant. My select looked like this:

from p in Person
select new Foo
{
  FullName = p.FirstName + ' ' + p.LastName
}

The boolean conditionals I had elsewhere in the query (i.e. "where p.IsActive") worked fine. I had to switch to using a string:

from p in Person
select new Foo
{
  FullName = p.FirstName + " " + p.LastName
}

This obviously is not the answer to the OP's question, but I was unable to find a similar question with the char/string issue so I wanted to post it for others' benefit.

David Peters
  • 1,938
  • 1
  • 20
  • 18
2

Just wanted to point out, you could have also used tender.HasAdminApproved.HasValue.Equals(true))... this works when bool allows nulls

Scott
  • 159
  • 2
  • 5