Using C# Expressions to build Array.All for Entity Framework

65 views Asked by At

I'm building a SQL "WHERE" clause dynamically using the System.Linq.Expressions.Expression class.

There are two tables Report and Document with relation one to many

public class Report
{
    public string Year { get; set; }
    public ICollection<Documents>? Documents { get; set; }
}

public class Documents
{
    public string Year { get; set; }
    public Report? Report { get; set; }
    public string Type { get; set; }
}

Linq Query to be replaced by Expression:

query.Where(x => x.Report.Documents.All(c =>( c.Type =="R" || c.Type =="RX") && c.Year==x.Report.Year))

What I archived so far is

private Expression GetExpression(Expression memberExpression)
{
   Expression<Func<ICollection<Documents>, bool>> containsExpr 
                    = (ICollection<Documents> q) => q.All((Func<Documents, bool> )null);
   var containsMethod = (containsExpr.Body as MethodCallExpression).Method;
                       Expression<Func<Documents, bool>> contains = x => x.Type =="R";
                      
   MemberExpression collectionPropertyAccessor = Expression.Property(memberExpression, "Documents");
  var targetCodesContains = Expression.Call(containsMethod, collectionPropertyAccessor, contains);
  return  binaryExpression =  Expression.And(targetCodesContains, targetCodesContains);
}
0

There are 0 answers