Yes, you can avoid the Compile().Invoke() which causes the query to execute in memory rather than being translated to the underlying query provider. Here are two better approaches:
If you need to keep the join structure, you can compose the expressions:
csharp
public IQueryable<ProjectedType> GetTargetGroupOfOpportunity<ProjectedType>(
EntityReference opportunityId,
Expression<Func<lbem_target_group, ProjectedType>> selector)
where ProjectedType : class
{
if (opportunityId == null)
{
return null;
}
// Create expression for anonymous type to target group
var param = Expression.Parameter(typeof(lbem_target_group), "tg");
var anonymousType = new { targetGroup = default(lbem_target_group), opportunity = default(Opportunity) };
var anonymousParam = Expression.Parameter(anonymousType.GetType(), "x");
var memberAccess = Expression.PropertyOrField(anonymousParam, "targetGroup");
// Replace parameter in selector body
var visitor = new ParameterReplacerVisitor(selector.Parameters[0], memberAccess);
var newBody = visitor.Visit(selector.Body);
// Create new lambda for the anonymous type
var combinedSelector = Expression.Lambda<Func<dynamic, ProjectedType>>(newBody, anonymousParam);
return CachelessServiceContext
.lbem_target_groupSet
.Join(
CachelessServiceContext.OpportunitySet,
targetGroup => targetGroup.lbem_target_groupId,
opportunity => opportunity.lbem_target_group_id.Id,
(targetGroup, opportunity) => new { targetGroup, opportunity })
.Where(x => x.opportunity.OpportunityId == opportunityId.Id
&& x.opportunity.lbem_target_group_id != null)
.Select(combinedSelector);
}
// Helper class for parameter replacement
private class ParameterReplacerVisitor : ExpressionVisitor
{
private readonly Expression _oldParameter;
private readonly Expression _newExpression;
public ParameterReplacerVisitor(Expression oldParameter, Expression newExpression)
{
_oldParameter = oldParameter;
_newExpression = newExpression;
}
protected override Expression VisitParameter(ParameterExpression node)
{
return node == _oldParameter ? _newExpression : base.VisitParameter(node);
}
}
Option 1 is recommended because:
It's simpler and more readable
It avoids the complexity of expression manipulation
It should translate properly to FetchXML/QueryExpression in Dynamics 365
It avoids materializing the query in memory
The key issue with your original code is that Compile().Invoke() forces LINQ to Objects evaluation instead of allowing the query provider to translate the expression tree to the appropriate query language (FetchXML in Dynamics 365's case).