简体   繁体   English

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

[英]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 问题是我在20-30个属性中选择了,每次我需要更改的唯一内容就是名称

Any suggestion how to go about it? 有什么建议怎么办呢?

You can use LinqKit package AsExpandable / Invoke extension methods: 您可以使用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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM