从表达式中的集合访问嵌套属性

本文关键字:访问 嵌套 属性 集合 表达式 | 更新日期: 2023-09-27 18:03:54

为了稍微设置一下上下文我正在使用一个表达式树构建一个动态Linq搜索子句使用这个类

public class HomeTableInvoice {
    public int Sys_InvoiceID { get; set; }
    public bool Turnover { get; set; }
    public int FK_StatusID { get; set; }
    public string InvoiceNumber { get; set; }
    public DateTime InvoiceDate { get; set; }
    public string DocType { get; set; }
    public ICollection<InvoiceCustomFields> InvoiceCustomFields { get; set; }
}

我已经设法让一切工作,我使用的参数是HomeTableInvoice,我可以得到一个属性的表达式使用

var parameter = Expression.Parameter(typeof(HomeTableInvoice), "invoice");
prop = Expression.Property(param, filter.SysName);

与过滤器。SysName是我希望过滤的字段。

当试图为底部的iccollection构建表达式时,问题就出现了。类InvoiceCustomFields包含

public class InvoiceCustomFields : CustomFieldsBase {
        public int? FK_SysInvoiceID { get; set; }    
        public string FK_CustomFieldHeader { get; set; }    
        public string Value { get; set; }    
    }

我试图访问字符串的FkCustomFieldHeader和字符串的值所以当我查询例如条件可以看起来像

where InvoiceNumber == 34 AndAlso (Invoice.InvoiceCustomField.FK_CustomFieldHeader == "Test" && Invoice.InvoiceCustomField.FK_CustomFieldHeader.Value == 42)

我试过使用

prop = Expression.PropertyOrField(Expression.PropertyOrField(param, "InvoiceCustomFields"), "FK_CustomFieldHeader");

但是会抛出这个错误

FK_CustomFieldHeader' is not a member of type 'System.Collections.Generic.ICollection`1[APData.Audit.Entityframework.Entities.InvoiceCustomFields]'

非常感谢您的帮助

——编辑——

在尝试Ivan的答案后,我得到了错误

No generic method 'Any' on type 'System.Linq.Enumerable' is compatible with the supplied type arguments and arguments

I then try this

prop = Expression.PropertyOrField(parameter, "InvoiceCustomFields");
   var queryableType = typeof(Enumerable);
   var whereMethod = queryableType.GetMethods()
      .First(m => {
         var parameters = m.GetParameters().ToList();                               
             return m.Name == "Any" && m.IsGenericMethodDefinition &&
                                                 parameters.Count == 2;
                       });
   MethodInfo methoInfo = whereMethod.MakeGenericMethod(prop.Type);
   var x = Expression.Call(methoInfo, Expression.PropertyOrField(parameter, "InvoiceCustomFields"), whereQuery);

然后抛出

Expression of type `'System.Collections.Generic.ICollection`1[InvoiceCustomFields]' cannot be used for parameter of type 'System.Linq.IQueryable`1[System.Collections.Generic.ICollection`1[InvoiceCustomFields]]' of method 'Boolean Any[ICollection`1](System.Linq.IQueryable`1[System.Collections.Generic.ICollection`1[InvoiceCustomFields]], System.Linq.Expressions.Expression`1[System.Func`2[System.Collections.Generic.ICollection`1[.InvoiceCustomFields],System.Boolean]])`

从表达式中的集合访问嵌套属性

让我们看看如果它不是动态的会是什么样子。如下:

Expression<Func<HomeTableInvoice, bool>> predicate = invoice =>
    invoice.InvoiceCustomField.FK_CustomFieldHeader == "Test" &&
    invoice.InvoiceCustomField.Value == "42";

不是一个有效的表达式。

你真正需要做的是像这样:

Expression<Func<HomeTableInvoice, bool>> predicate = invoice =>
    invoice.InvoiceCustomFields.Any(field => 
        field.InvoiceCustomField.FK_CustomFieldHeader == "Test" &&
        field.InvoiceCustomField.Value == "42");

这是你如何动态地构建(希望你可以根据你的需要调整它,用你的变量替换硬编码的部分):

var parameter = Expression.Parameter(typeof(HomeTableInvoice), "invoice");
var fieldParameter = Expression.Parameter(typeof(InvoiceCustomFields), "field");
var anyPredicate = Expression.Lambda(
    Expression.AndAlso(
        Expression.Equal(
            Expression.PropertyOrField(fieldParameter, "FK_CustomFieldHeader"),
            Expression.Constant("Test")),
        Expression.Equal(
            Expression.PropertyOrField(fieldParameter, "Value"),
            Expression.Constant("42"))),
    fieldParameter);
var fieldCondition = Expression.Call(
    typeof(Enumerable), "Any", new[] { fieldParameter.Type },
    Expression.PropertyOrField(parameter, "InvoiceCustomFields"), anyPredicate);
// You can use the fieldCondition in your combinator,
// the following is just to complete the example
var predicate = Expression.Lambda<Func<HomeTableInvoice, bool>>(fieldCondition, parameter);
// Test
var input = new List<HomeTableInvoice>
{
    new HomeTableInvoice
    {
        InvoiceNumber = "1",
        InvoiceCustomFields = new List<InvoiceCustomFields>
        {
            new InvoiceCustomFields { FK_CustomFieldHeader = "Test", Value = "42" }
        }
    },
}.AsQueryable();
var output = input.Where(predicate).ToList();