Hi,
Consider the following Linq query:
var count = (from cb in metaData.CountBlock
where cb.CompanyId == Entity.CompanyId
&& (cb.SiteId == Entity.SiteId || !cb.SiteId.HasValue)
select cb.CountBlockId).Count();
SiteId and Entity.SiteId are both of type int?.
When executed this generates the following exception:
System.InvalidOperationException: The binary operator Equal is not defined for the types 'System.Nullable`1[System.Int32]' and 'System.Int32'.
at System.Linq.Expressions.Expression.GetEqualityComparisonOperator(ExpressionType binaryType, String opName, Expression left, Expression right, Boolean liftToNull)
at System.Linq.Expressions.Expression.Equal(Expression left, Expression right, Boolean liftToNull, MethodInfo method)
at System.Linq.Expressions.Expression.MakeBinary(ExpressionType binaryType, Expression left, Expression right, Boolean liftToNull, MethodInfo method, LambdaExpression conversion)
at System.Linq.Expressions.Expression.MakeBinary(ExpressionType binaryType, Expression left, Expression right, Boolean liftToNull, MethodInfo method)
at SD.LLBLGen.Pro.LinqSupportClasses.ExpressionHandlers.GenericExpressionHandler.HandleBinaryExpression(BinaryExpression expressionToHandle)
at SD.LLBLGen.Pro.LinqSupportClasses.ExpressionHandlers.PreProcessor.HandleBinaryExpression(BinaryExpression expressionToHandle)
at SD.LLBLGen.Pro.LinqSupportClasses.ExpressionHandlers.GenericExpressionHandler.HandleBinaryExpressionBooleanOperator(BinaryExpression expressionToHandle)
etc...
Which is strange, because both are of type int?, so where does the type int come from?
When I change my code to the following, it works:
int siteId = Entity.SiteId.GetValueOrDefault(0);
var metaData = new LinqMetaData();
var count = (from cb in metaData.CountBlock
where cb.CompanyId == Entity.CompanyId
&& (cb.SiteId == siteId || !cb.SiteId.HasValue)
select cb.CountBlockId).Count();
Note that I have to assign the result of GetValueOrDefault() to a variable, because when I would include the method call in the Linq query itself I get a conversion exception.
Clearly, this is not what I want because it forces me to add extra unnecessary code.
BTW, this only happens when the code (which is contained in the Business Layer) is called from an ASP.Net website. When called from my unit tests, it works correctly. Kinda strange, I know...
Kind regards,
Patrick