Where condition and Dynamics 365 LINQ Provider

Today I got a pull request to review and it had some code in it that I thought would not work. The code in questions looked similar to

var allAccountsForPrimaryContact = 
			proxy
			.CreateQuery<Account>()
			.Where(t => t.PrimaryContactId == contactEntityRef)
			.ToList();

This made me write a comment that it would perform an invalid comparison and never return any results at all, but to my surprise when I tested the code it actually returned the expected results.

This made me dig a little bit deeper, and I went on to decompile the Microsoft.Xrm.Sdk assembly, and I look at the code for the queryprovider. In there I saw the code below which made me realize that I can actually use objects directly in Where condtions in a couple of cases, namely when the object is an EntityReference, Money, OptionSet or an value of type Enum.

private object TranslateExpressionToConditionValue(Expression exp, params ParameterExpression[] parameters)
{
	object obj = TranslateExpressionToValue(exp, parameters);
	EntityReference entityReference = obj as EntityReference;
	OptionSetValue optionSetValue = obj as OptionSetValue;
	Money money = obj as Money;
	if (entityReference != null)
	{
		obj = entityReference.Id;
	}
	else if (money != null)
	{
		obj = money.Value;
	}
	else if (optionSetValue != null)
	{
		obj = optionSetValue.Value;
	}
	else if (obj != null && obj.GetType().IsEnum)
	{
		obj = (int)obj;
	}
	return obj;
}

Leave a comment