Wednesday, June 29, 2016

Unable to create a constant value of type 'System.Object'. Only primitive types or enumeration types are supported in this context.

 Problem:

Working a dynamic linq issue.  Using the great helper class, Predicate Builder posted over on the O'Reilly site.  I had built out my query and it worked great against my EF generated class.  Then I started getting this error each time I ran the predicate builder against a data type of nullable Guid.  I searched around on line at some more in depth explanations.  But nothing seemed to really fit my problem.

Solution:

Then I took the simple advice given on stackoverflow.  I changed the following lines
 


var race = Guid.Parse(race_ID);
predicate = predicate.Or(l => l.Race_ID.Equals(race));


to


var race = Guid.Parse(race_ID);
predicate = predicate.Or(l => l.Race_ID==race);

C# interpreter at work here: 

"When == is used on an expression of type object, it'll resolve to System.Object.ReferenceEquals.
Equals is just a virtual method and behaves as such, so the overridden version will be used (which, for string type compares the contents). "


so we could also do




var race = Guid.Parse(race_ID);
predicate = predicate.Or(l => l.Race_ID.Value.Equals(race));

Source:

  1. http://www.albahari.com/nutshell/predicatebuilder.aspx
  2. http://stackoverflow.com/questions/4592432/linq-query-keeps-throwing-unable-to-create-a-constant-value-of-type-system-obje
  3. http://stackoverflow.com/questions/814878/c-sharp-difference-between-and-equals

Thursday, June 2, 2016

Unable to create a constant value of type 'System.Object'

Problem:

I had a class created using the EF tools.  It generated a field which was a nullable Guid.  The datatype declaration was:


Guid? Status_ID


Each time I ran my controller code to build out my query.  I ran the code


Guid? ms_ID = Guid.Parse(MilitaryStatus_ID);
predicate = predicate.Or(l => l.MilitaryStatus_ID.Equals(ms_ID));


This would always through the unknown system.object error.  It was driving me crazy.


Solution:

I did not have any issues against data types of Guid which lead me to think about the nullable operator.  This seemed to be the issue so I removed it for testing and was able to run the above code no problems.  Thus realized that the issue was Linq not dealing with the nullable condition of my variable correctly.  Thus the work around was  to use == instead of Equals operator.


Guid? ms_ID = Guid.Parse(MilitaryStatus_ID);
predicate = predicate.Or(l => l.MilitaryStatus_ID == ms_ID);



Source:

http://stackoverflow.com/questions/4592432/linq-query-keeps-throwing-unable-to-create-a-constant-value-of-type-system-obje