簡體   English   中英

使用表達式樹過濾

[英]Filter using Expression Trees

我需要查詢數據庫並根據傳遞給函數的參數進行過濾。 我傳遞了兩個日期參數(用作日期范圍),一個名稱和一個狀態參數。 所有參數都可以具有“和”或“或”條件。 基本上,我想基於填充了哪些參數來構建linq表達式,並將其傳遞給Entity Framework以返回結果集。

我如何用最少的“ if”語句來做到這一點? 如果您足夠友善地提供示例代碼的說明,那就太好了。 我正在嘗試學習表達式樹,因此進行解釋會有所幫助。

此時,我沒有太多代碼。 這就是為什么我在這里發布。 我可以列出方法簽名。 您到底在找什么?

public enum EmployeeStatus
{
    FullTime,
    PartTime,
    Contract
}

public IEnumerable<Employee> FilterEmployees(DateTime? startDate, 
    DateTime? endDate, string employeeName, EmployeeStatus employeeStatus)
{   }
public IQueryable<Employee> FilterEmployees(IQueryable<Employee> query, DateTime? startDate, DateTime? endDate, string employeeName, EmployeeStatus employeeStatus)
{
    if (startDate != null)
        query = query.Where(x => x.StartDate >= startDate);

    // etc...

    return query;
}

所有參數都可以具有“和”或“或”條件。 -您可以考慮使用PredicateBuilder。 參見http://www.albahari.com/nutshell/predicatebuilder.aspx 為什么? 因為這允許您編寫單個查詢,但是僅在需要時才添加AND / OR謂詞。 您可能需要或可能不需要此功能,但是要意識到它是一個很好的功能。 在實際調用查詢之前,沒有數據庫開銷-它提供了一種有條件地構建IQueryable的方法,在該條件下您可能不想在某些條件下與字段進行匹配。 例如,前幾天我用它來忽略輸入字符串少於10個字符的搜索的產品代碼字段(最小長度為10)。

這將允許您使用if條件添加AND / OR語句,如下所示:

public IQueryable<Employee> FilterEmployees(IQueryable<Employee> query, DateTime startDate, DateTime endDate, string employeeName, EmployeeStatus employeeStatus)
{
    var predicate = PredicateBuilder.True<Employee>();

    //All names starting with 'A'
    predicate = predicate.And(x => x.Name.StartsWith("A"));

    //Add a condition only if the employee is PartTime
    if (employeeStatus == EmployeeStatus.PartTime)
    {
        //Add condition for when they start
        predicate = predicate.And(x => x.StartDate >= startDate);
    }
    else
    {
        //Say we don't care about the start date for the other employee statuses,
        //but we want to add condition for when non-part-time employees are due to leave
        predicate = predicate.And(x => x.EndDate <= endDate);
        //or their name ends in 'z'
        predicate = predicate.Or(x => x.Name.EndsWith("z"));
    }

    IQueryable<Employee> employees = query.FindBy(predicate); //you should probably use a repository here to return your query

    return employees

}

注意-這旨在作為偽代碼來演示,並且可能有錯誤-請參見上面的鏈接以獲取正確的實現。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM