2015-05-28 74 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));