LINQの主なポイントは、強く型付けされたアクセスをされたので、私はできる限りの動的LINQを避けるためにしようとしています。動的linqの使用は解決策ですが、linqの目的とはまったく反対であり、ESQLを使用して、スティング連結からクエリを構築するのにはかなり近いです。とにかく動的linqは時にはリアルタイムの節約になります(特に複雑な動的順序付けの場合)、Linq-to-SQLを使った大規模なプロジェクトでもうまく使用できます。これは、一般的な解決策ではありません
public static IQueryable<SomeClass> Filter(this IQueryable<SomeClass> query, SearchCriteria filter)
{
if (filter.Property1 != null) query = query.Where(s => s.Property1 == filter.Property1);
if (filter.Property2 != null) query = query.Where(s => s.Property2 == filter.Property2);
return query;
}
:
public class SearchCriteria
{
public string Property1 { get; set; }
public int? Property2 { get; set; }
}
とヘルパークエリ拡張メソッドのように:私は通常、いくつかのSearchCriteria
クラスのように定義されない
。やはり一般的な解決策は、いくつかの振る舞いを共有するクラスの厳密な型付けされた処理です。
より複雑な解決策は、述語ビルダーとビルド式ツリーを使用することですが、式ツリーを作成することは、文字列を連結してESQLクエリを構築するほうがずっと複雑です。
public T Get<T>(string property, object value) : where T is Account
{
//p
var p = Expression.Parameter(typeof(T));
//p.Property
var propertyExpression = Expression.Property(p, property);
//p.Property == value
var equalsExpression = Expression.Equal(propertyExpression, Expression.Constant(value));
//p => p.Property == value
var lambda = Expression.Lambda<Func<T,bool>>(equalsExpression, p);
return context.Set<T>().SingleOrDefault(lambda);
}
それはEF 5のSet<T>()
メソッドを使用しています。