A very obscure ObjectQuery exception

by Charles Cherry

A co-worker was having problems trying to find the cause of this exception, which had him stopped in his tracks:

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

It was happening while trying to loop through the results of an Entity Framework query:

       var q = (from c in _entities
                          join d in _db.Agencies on c.FKAgencyID equals d.AgencyID
                          orderby c.LastName, c.FirstName
                          select new {

           foreach (var i in q)
              SearchResultEntity result = new SearchResultEntity();
              result.EmployeeId = i.EmployeeID;
              result.FirstName = i.FirstName;
              result.LastName = i.LastName;
              result.LastFour = i.Last4SSN;

This was a bugger to debug, but In the end I finally found the culprit. He had previously run code similar to this to add filters before actually expanding the results:

if (agencyId != null )
    _entities = from c in _entities
        join d in _db.Agencies on c.FKAgencyID equals d.AgencyID
        where d.AgencyID.Equals(agencyId)
        select c;

It turns out that “agencyId” was defined as a Nullable GUID, and the Linq expression converter apparently doesn’t like nullable GUIDs.

We added the line:

Guid NewAgencyId = new Guid(agencyId.Value.ToString());

just above the line:

    _entities = from c in _entities

and changed the expression to evaluate against the new, non-nullable version of the agencyId:

    where d.AgencyID.Equals(NewAgencyId)

and everything worked as expected.

Like I said, this was a bugger to track down. There are lots of posts out there concerning this exception, but none of them dealt with nullable types like this, and none of them seemed to match our scenario.

I’ll need to remember this little gotcha.