2015-05-28 75 views
0

所以我有一个实体叫Customer。客户有name,address,gender,birthdate,citynumber of kids动态查询与实体框架

我想让用户可以在这些字段上进行非常动态的过滤。例如。他可以添加一个文本域来过滤名称,然后添加另一个过滤另一个名称,然后添加另外两个文本域以在两个日期之间过滤出生日期等等...用户还可以选择过滤到日期或等于一个日期。所以事先并不知道用户想要应用多少个过滤器。

我该如何构建这种查询,最好是使用LINQ?

在此先感谢。

+1

您是否尝试过的东西? – Mairaj

+0

搜索'.net查询生成器',你应该找到可以为你做这件事的工具。 –

+0

感谢@AlaaMasoud,我发现了一个NuGet包DbExtensions,并且在经过一些试验和错误之后,做出了这个诀窍! –

回答

0

为ASP.NET MVC 4搜索动态Linq查询生成器。它是一个nuget包,允许您进行动态linq查询。

0

这将与您如何编写SQL查询类似,检查是否给出参数,然后将其作为过滤器应用。

public class Customer 
    { 
     public string Name; 
     public string Address; 
     public string City; 
     public string Gender; 
     public DateTime Birthdate; 
     public int NumberOfKids; 
    } 

    public IEnumerable<Customer> CustomerSearch(
     string partialName = null, 
     string partialAddress = null, 
     string partialCity = null, 
     string gender = null, 
     DateTime? exactBirthdate = null, 
     DateTime? startDate = null, 
     DateTime? endDate = null, 
     int? minNumberOfKids = null) 
    { 
     // Sample data 
     var customers = new [] { 
      new Customer { Name = "Jack", Birthdate = DateTime.Today.AddYears(-30), NumberOfKids = 1 }, 
      new Customer { Name = "Jill", Birthdate = DateTime.Today.AddYears(-33).AddMonths(3), NumberOfKids = 2 }, 
      new Customer { Name = "Bob", Birthdate = DateTime.Today.AddYears(-35), NumberOfKids = 3 } 
     }; 
     var query = 
      from c in customers 
      where (String.IsNullOrWhiteSpace(partialName) || c.Name.Contains(partialName)) 
       && (String.IsNullOrWhiteSpace(partialAddress) || c.Address.Contains(partialAddress)) 
       && (String.IsNullOrWhiteSpace(partialCity) || c.City.Contains(partialCity)) 
       && (String.IsNullOrWhiteSpace(gender) || c.Gender == gender) 
       && (!exactBirthdate.HasValue || c.Birthdate.Date == exactBirthdate.Value.Date) 
       && (!startDate.HasValue || !endDate.HasValue || c.Birthdate.Date >= startDate.Value.Date && c.Birthdate.Date <= endDate.Value.Date) 
       && (!minNumberOfKids.HasValue || c.NumberOfKids >= minNumberOfKids.Value) 
      select c; 
     return query; 
    } 

,并调用它是这样的:

 test.CustomerSearch("J", minNumberOfKids: 2).ToList().ForEach(c => Console.WriteLine("J and 2 kids " + c.Name)); 
     test.CustomerSearch(exactBirthdate: DateTime.Today.AddYears(-35)).ToList().ForEach(c => Console.WriteLine("exact birthdate " + c.Name)); 
     test.CustomerSearch(startDate: DateTime.Today.AddYears(-36), endDate: DateTime.Today.AddYears(-31)).ToList().ForEach(c => Console.WriteLine("birthdate between " + c.Name));