2016-11-07 99 views
4

通過我在實體框架,看起來像基於謂詞實體框架C#選擇在方法

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種性質和我每次都需要改變的僅僅是名稱

任何建議如何去解決它?

回答

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

非常感謝金正日看看它 – CMS