0

関数に渡されたパラメーターに基づいて、データベースにクエリを実行し、フィルター処理する必要があります。2 つの日付パラメーター (日付範囲として使用)、名前、およびステータス パラメーターを渡しています。すべてのパラメーターは、「and」または「or」条件を持つことができます。基本的に、入力されたパラメーターに基づいて linq 式を作成し、それを Entity Framework に渡して結果セットを返したいと思います。

最小限の「if」ステートメントでこれを行うにはどうすればよいですか? サンプルコードで説明を提供できるほど親切にできれば、それは素晴らしいことです. 式ツリーを学習しようとしているので、説明が役立ちます。

この時点で、私は多くのコードを持っていません。そのため、ここに投稿しました。メソッドのシグネチャを一覧表示できます。正確には何を探していますか?

public enum EmployeeStatus
{
    FullTime,
    PartTime,
    Contract
}

public IEnumerable<Employee> FilterEmployees(DateTime? startDate, 
    DateTime? endDate, string employeeName, EmployeeStatus employeeStatus)
{   }
4

2 に答える 2

4
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;
}
于 2012-11-08T15:53:26.963 に答える
2

すべてのパラメーターは、「and」または「or」条件を持つことができます。-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

}

注-これは、デモンストレーション用の疑似コードとして意図されており、エラーが発生する可能性があります-適切な実装については、上記のリンクを参照してください。

于 2012-11-09T02:13:30.640 に答える