9

Customersテーブルがあり、次のようにフィルタリングしたいとします。

  • 国:すべて、米国、英国、カナダ
  • 収入:すべて、低、高、中
  • 年齢:すべて、ティーンエイジャー、大人、シニア

このフィルターのSQL文字列を作成する必要がある場合は、次のようになります。

if (Country != "All") sql += "country = " + Country
if (Income != "All") sql += "and income = " + Income
if (Age != "All") sql += "and age = " + Age;

したがって、基本的に、ユーザーは一部のフィールドでフィルター処理できますが、すべてのフィールドでフィルター処理する必要はありません。

Entity Frameworkを使用してこれをどのように行いますか?

ありがとう !

4

3 に答える 3

25

LINQ to EntityクエリはIQueryable'sを返すため、次のようにクエリを作成できます。

IQueryable<Person> query = context.People;

if (Country != "All")
{
    query = query.Where(p => p.Country == Country);
}

if (Income != "All")
{
    query = query.Where(p => p.Income == Income);
}

if (Age != "All")
{
    query = query.Where(p => p.Age == Age);
}

List<Person> fetchedPeople = query.ToList();

このケースはほとんど単純すぎますが、フィルタリングを動的に追加する必要があるより複雑な状況で非常に役立ちます。

于 2012-07-13T07:27:18.060 に答える
12

この方法で条件付きパラメーターを含めることができます。

return Customers.Where(
                customer =>
                customer.Name == Name &&
                (Age == "All" || customer.Age == Age) &&
                (Income == "All" || customer.Income == Income) &&
                (Country == "All" || customer.Country == Country)
                ).ToList();

ある条件が真の場合(たとえば、国がに等しい場合All)、すべてのパラメーター条件が真になり、このパラメーターは結果をフィルター処理しません。

于 2012-07-13T07:18:08.857 に答える
0

拡張メソッドを使用して、読み取り可能で保守可能なコードを支援できます。

  • LinqExtensions.cs
public static class LinqExtensions
{
    public static IQueryable<TSource> WhereIf<TSource>(this IQueryable<TSource> source, bool condition, Expression<Func<TSource, bool>> predicate)
    {
        return condition ? source.Where(predicate) : source;
    }
}
  • コードのリファクタリング
List<Person> peoples = context.People
    .WhereIf(Country != "All", p => p.Country == Country)
    .WhereIf(Income != "All", p => p.Income == Income)
    .WhereIf(Age != "All", p => p.Age == Age)
    .ToList();
于 2021-11-29T03:01:16.303 に答える