How to Append to an expression

后端 未结 8 1557
清歌不尽
清歌不尽 2020-12-05 01:46

Based on my question from yesterday:

if I had to append to my existing \'where\' expression, how would i append?

Expression

        
8条回答
  •  一个人的身影
    2020-12-05 02:28

    It´s not exactly the answer for your question, but, I was looking for the same thing you are, and then I've found a better answer to my question.

    Instead of building a dynamic Expression, you could retrieve the IQueryable and then filter what you want like this:

    var customers = CustomerRepository.AllEntities();
    
    if (!forename.IsNullOrEmpty())
        customers = customers.Where(p => p.Forename == forename);
    if (!familyname.IsNullOrEmpty())
        customers = customers.Where(p => p.FamilyNames.Any(n => n.Name==familyname));
    if (dob.HasValue)
        customers = customers.Where(p => p.DOB == dob);
    

    Note: I was concerned about executing more then one ".Where" statement because I was afraid this would generate more than one query in the DataBase, or because I would have to retrive all records and then filter them, but this is not true, Linq dynamic generate just one query only when you call .ToList() method.

    Here you can see original question that I've took the example from.

提交回复
热议问题