2016-08-24 4 views
3

Ok, чтобы установить контекст немного я построение динамического пункт поиска Linq, используя дерево выражения с помощью этого классаДоступ к вложенному свойству из коллекции в Expression

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); 

с 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]' 

любая помощь очень ценится

--Edit--

После попытки ответ Ивана я получаю ошибку

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]])` 

ответ

2

Посмотрите, как это выглядит, если оно не динамическое. Ниже приводится следующее:

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(); 
+0

Я получаю сообщение об ошибке Нет универсального метода «Любой» в типе «System.Linq.Enumerable» совместим с аргументами и аргументами поставляемого типа. –

+0

Это странно, потому что я тестировал его, и он работает без проблем (см. Обновленный ответ с тестовым кодом в конце). –

+0

См. Мой ответ для ответа :) спасибо за помощь до сих пор –

Смежные вопросы