C # Entity Framework Select based on predicate passed by method

I have a request in the Entity Framework that looks like

context.Customers.Where(c => c.IsActive == true)
                .Select(c => new
                {
                    Name = c.First + ' ' + c.Last,
                    SomeMoreInfo = true
                })

It was repeatedly used in the code.

so I have a method similar to this

  public List<CustomerVM> SelectCustomerNames(string filter){
       return context.Customers.Where(c => c.IsActive == true)
                        .Select(c => new CustomerVM
                        {
                            Name = c.First + ' ' + c.Last,
                            SomeMoreInfo = true
                        })
                        .Where(c=>c.Name.StartsWith(filter))
                        .ToList();
      }

The fact is that sometimes I need to get a name differently, for example

Name = c.First + ' ' + c.Last
Name = c.First
Name = c.Last
Name = c.Last + ' ' + c.Middle + ' ' + c.Last
Name = c.First + (join is some other table ...)

I would like to have a function that should look like this:

  public List<CustomerVM> SelectCustomerNames(string filter,Expression<Func<Customer, string>> nameSelectorPredicate){
       return context.Customers.Where(c => c.IsActive == true)
                        .Select(c => new CustomerVM
                        {
                            Name = nameSelectorPredicate,
                            SomeMoreInfo = true
                        })
                        .Where(c=>c.Name.StartsWith(filter))
                        .ToList();
      }

The fact is that I have a choice, for example, 20-30 properties, and the only thing I need to change every time is the name

Any suggestion how to do this?

+4
source share
1 answer

You can use the LinqKit package AsExpandable/ Invokeextension methods:

public List<CustomerVM> SelectCustomerNames(string filter, Expression<Func<Customer, string>> nameSelector)
{
    return context.Customers.AsExpandable()
        .Where(c => c.IsActive == true)
        .Select(c => new CustomerVM
        {
            Name = nameSelector.Invoke(c),
            SomeMoreInfo = true
        })
        .Where(c => c.Name.StartsWith(filter))
        .ToList();
}
+2
source

Source: https://habr.com/ru/post/1660030/


All Articles