3
OK设置上下文一点使用表达式树使用这个类访问嵌套属性从集合中的表达
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; }
}
我设法让一切工作我建立了一个动态的LINQ搜索子句和我用的参数是HomeTableInvoice,我可以使用
var parameter = Expression.Parameter(typeof(HomeTableInvoice), "invoice");
prop = Expression.Property(param, filter.SysName);
与filter.SysName是我要过滤的字段得到一个表达式的属性。
当试图在底部为ICollection构建表达式时,问题就出现了。类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]'
任何的帮助深表感谢
- 编辑 -
由伊万试图回答后,我得到的错误
No generic method 'Any' on type 'System.Linq.Enumerable' is compatible with the supplied type arguments and arguments
我又试图此
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]])`
我收到错误没有类型'System.Linq.Enumerable'的泛型方法'Any'与提供的类型参数和参数兼容。 –
这很奇怪,因为我已经测试过它,它的工作没有问题(请参阅最后的测试代码更新后的答案)。 –
请参阅我的更新回答:)感谢您的帮助至此 –