I'm trying to translate the following LINQ query into expression tree
var queryActivity = uow.PromoActivityMeasuresRepository.ToQueryable();
var queryMeasure = uow.PromoMeasuresRepository.ToQueryable();
queryActivity.Where(pa => pa.WorkSpaceId == 28 &&
!queryMeasure.Any(pm => pm.WorkSpaceId == pa.WorkSpaceId &&
pm.Organization == pa.Organization &&
pm.MeasureCode == pa.MeasureCode));
I've been able to get expressions for what is related to the simple constraints, but now I'm stuck at how create the expression that relates on queryMeasure.Any
With code
//I've translated pm.WorkSpaceId == pa.WorkSpaceId
var childParameter = Expression.Parameter(childEntityType, "pa");
var parentParameter = Expression.Parameter(validatingEntityType, "pm");
var parentWorkSpace = Expression.Property(parentParameter, "WorkSpaceId");
var childWorkSpace = Expression.Property(childParameter, "WorkSpaceId");
var parentChildWorkSpaceConstraint = Expression.Equal(parentWorkSpace, childWorkSpace);
and with code
// I've translated pm => pm.WorkSpaceId == pa.WorkSpaceId &&
// pm.Organization == pa.Organization &&
// pm.MeasureCode == pa.MeasureCode)
Expression logicalAnd = null;
foreach (var field in FKChildEntity.Value.Fields)
{
var parentLeft = Expression.Property(parentParameter, field);
var childRight = Expression.Property(childParameter, field);
var parentChildConstraint = Expression.Equal(parentLeft, childRight);
if (logicalAnd == null)
{
logicalAnd = Expression.AndAlso(parentChildWorkSpaceConstraint, parentChildConstraint);
continue;
}
//parentConstraints.Add(parentChildConstraint);
logicalAnd = Expression.AndAlso(logicalAnd, parentChildConstraint);
}
And here the issue...
I'm not able to understand how can I call the queryMeasure.Any to be used after in the NegateExpression
var parentDelegateType = typeof(Func<,>).MakeGenericType(validatingEntityType, typeof(bool));
var parentPredicate = Expression.Lambda(parentDelegateType, logicalAnd, parentParameter);
var promoMeasuresParameter = Expression.Constant(dataRepository, dataRepository.GetType());
var AnyMethod = Expression.MakeMemberAccess(promoMeasuresParameter, promoMeasuresParameter.GetType().GetMember("Any").FirstOrDefault());
var parentQueryable = dataRepository.GetType().InvokeMember("ToQueryable", BindingFlags.InvokeMethod, null, dataRepository, null);
var collectionParameter = Expression.Parameter(parentQueryable.GetType(), "parentCollection");
var AnyMethodExpression = Expression.Call(parentQueryable.GetType(), "Any", null , parentPredicate);
var negateExpression = Expression.Negate(AnyMethodExpression);
Can I ask someone of you some hints on how to proceed ?
Thank you all