🧠 Expression Trees = Dynamic Queries
Statik sorgular yeterli değil. Expression Trees ile runtime’da dinamik LINQ sorguları oluşturun.
🎯 Expression Tree Örnekleri
// 1. Dinamik WHERE public static Expression> BuildFilter ( string propertyName, string operation, object value) { var parameter = Expression.Parameter(typeof(T), "x"); var property = Expression.Property(parameter, propertyName); var constant = Expression.Constant(value); Expression condition = operation switch { "Equals" => Expression.Equal(property, constant), "GreaterThan" => Expression.GreaterThan(property, constant), "LessThan" => Expression.LessThan(property, constant), "Contains" => Expression.Call(property, typeof(string).GetMethod("Contains", new[] { typeof(string) }), constant), _ => throw new NotSupportedException() }; return Expression.Lambda >(condition, parameter); } // 2. Dinamik OrderBy public static IQueryable OrderByDynamic ( this IQueryable query, string propertyName, bool ascending = true) { var parameter = Expression.Parameter(typeof(T), "x"); var property = Expression.Property(parameter, propertyName); var lambda = Expression.Lambda(property, parameter); var methodName = ascending ? "OrderBy" : "OrderByDescending"; var method = typeof(Queryable).GetMethods() .First(m => m.Name == methodName && m.GetParameters().Length == 2) .MakeGenericMethod(typeof(T), property.Type); return (IQueryable )method.Invoke(null, new object[] { query, lambda }); } // 3. Predicate Builder public static class PredicateBuilder { public static Expression > True () { return f => true; } public static Expression > And ( this Expression > expr1, Expression > expr2) { var invokedExpr = Expression.Invoke(expr2, expr1.Parameters); return Expression.Lambda >( Expression.AndAlso(expr1.Body, invokedExpr), expr1.Parameters); } }
✅ Expression Tree Kullanım Alanları
- ✓ Dinamik filtreleme
- ✓ Runtime sorgu oluşturma
- ✓ Özel LINQ provider’lar
- ✓ ORM sorgu optimizasyonu
- ✓ Rule engine implementasyonu
Expression Trees, C#’ın en güçlü özelliklerinden biridir. Runtime’da dinamik sorgular oluşturarak esnek çözümler üretebilirsiniz.
