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

No comments:

Post a Comment