使用 C# 表达式为实体框架构建 Array.All

问题描述 投票:0回答:0

我正在使用 System.Linq.Expressions.Expression 类动态构建 SQL“WHERE”子句。

有两张桌子 具有一对多关系的报表和文档

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.Where(x => x.Report.Documents.All(c =>( c.Type =="R" || c.Type =="RX") && c.Year==x.Report.Year))

我目前存档的是

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);
}
c# entity-framework linq expression linq-expressions
© www.soinside.com 2019 - 2024. All rights reserved.