Well, this is embarrassing. Remember that flogging I unleashed on unscrupulous developers being disrespectful to LINQ, performance and humanity in general? I was basking in my own cleverness of possessing the knowledge of LINQ operators including magic Any:
if(crm.OpportunitySet .Any(opp => opp.EstimatedValue >= 1000000m)) { // that would have been a winner if it worked }
Yesterday I had a chance to use what I preached and this is what I got in return:
System.NotSupportedException was unhandled
HResult=-2146233067
Message=The method ‘Any’ is not supported.
Source=Microsoft.Xrm.Sdk
That proves two things:
- Never assume anything when it comes to complex products like Dynamics CRM. Have a theory? Run a test – usually it does not take long.
- Support for LINQ syntax is a responsibility of LINQ-to-CRM provider that translates LINQ expressions into QueryExpression. LINQ providers are notoriously difficult to write and they are created by humans who pick their battles and choose spend time elsewhere but sweating on support for obscure operators that may end up never being used.
So what about that “yes/no” test? This is the best result so far:
if(null != crm.OpportunitySet .Where (opp => opp.EstimatedValue > 1000000m) .Select(opp => new { opp.OpportunityId }) .FirstOrDefault()) { Console.WriteLine("Computer says 'yes'!"); }
That LINQ results in not the best but still paltry SQL clause “select top 2 opportunityid from …”.