实体框架C#基于传递方法的Predicate进行选择

时间:2016-11-07 03:54:59

标签: c# entity-framework select

我在Entity Framework中有一个看起来像

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

它在代码中重复使用

所以我有一个看起来像这样的方法

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

事情是,有时我需要得到与

不同的名称
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 ...)

我想要一个看起来像这样的功能

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

事情就是我在选择20到30个属性中,每次我需要更改的唯一内容是名称

有任何建议如何去做?

1 个答案:

答案 0 :(得分:2)

您可以使用LinqKitAsExpandable / Invoke扩展程序:

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