CMS
CMS

Reputation: 3757

Entity Framework C# Select based on Predicate passed in method

I have a query in Entity Framework that looks like that

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

Its reused a lot in the code

so i have a method that looks like 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 thing is that sometimes i need to get the name differently like

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 thing is that i have in the select like 20 - 30 properties and the only thing i need changed each time is the name

Any suggestion how to go about it?

Upvotes: 4

Views: 1424

Answers (1)

Ivan Stoev
Ivan Stoev

Reputation: 205729

You can use LinqKit package AsExpandable / Invoke extension 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();
}

Upvotes: 2

Related Questions