我在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个属性中,每次我需要更改的唯一内容是名称
有任何建议如何去做?
答案 0 :(得分:2)
您可以使用LinqKit包AsExpandable
/ 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();
}