### C# Example: Dynamic Query with LinqKit Source: https://github.com/scottksmith95/linqkit/blob/master/README.md Demonstrates a C# LINQ query with dynamic parameters using LinqKit's AsExpandable(). This example simulates dynamic calculations within the query, which can lead to less optimized SQL if not handled properly. ```csharp var t = DateTime.Now.Month % 3; var qry1 = from o in context.Orders.AsExpandable() let myTemp = t == 1 ? o.Amount + 10 : t == 2 ? o.Amount - 10 : o.Amount select new { OrderDate = o.OrderDate, FixedAmount = myTemp }; var qry2 = from x in qry1 where x.FixedAmount < 100 select x; var res = qry2.ToList(); ``` -------------------------------- ### PredicateBuilder Initialization (True) Source: https://github.com/scottksmith95/linqkit/blob/master/README.md This C# code illustrates how PredicateBuilder.New(true) can be a shortcut for creating an initial expression that evaluates to true. This is useful when starting an AND-based predicate. ```csharp var predicate = PredicateBuilder.New(true); ``` -------------------------------- ### LINQKit and EF Core Example: Aggregating Order Amounts Source: https://github.com/scottksmith95/linqkit/blob/master/README.md This C# code demonstrates a complete Entity Framework and LINQKit integration example. It defines an Order entity, a DbContext, and performs a query that groups orders by 'OrderDate' and calculates the average 'Amount' using an expression. It utilizes `AsExpandable()` for LINQKit query processing and `ToList()` to execute the query. ```csharp using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using LinqKit; // ... (Order and MyDbContext definitions) class Program { static void Main(string[] args) { Expression, decimal?>> expression = orders => orders.Average(o => (decimal?)o.Amount); using (var context = new MyDbContext()) { IQueryable orders = context.Orders; var q = from o in orders.AsExpandable() group o by o.OrderDate into g select new { OrderDate = g.Key, AggregatedAmount = expression.Invoke(g.AsQueryable()) }; //ToList or ToListAsync: q.ToList().ForEach(Console.WriteLine); Console.ReadLine(); } } } ``` -------------------------------- ### PredicateBuilder Initialization (False) Source: https://github.com/scottksmith95/linqkit/blob/master/README.md This C# code illustrates how PredicateBuilder.New() can be a shortcut for creating an initial expression that evaluates to false. This is particularly relevant when starting an OR-based predicate. ```csharp Expression> predicate = c => false; ``` -------------------------------- ### C# Example: Dynamic Expression Optimizer with LinqKit Source: https://github.com/scottksmith95/linqkit/blob/master/README.md Shows how to apply the expression optimizer dynamically for a specific query by passing an optimizer function to the `AsExpandable` method. This allows for selective optimization of LINQ queries. ```csharp // define the optimizer you want to use var optimizer = ExpressionOptimizer.visit; // simulate some dynamic non-database-parameter var t = DateTime.Now.Month % 3; // provide the optimizer in the AsExpandable call var qry1 = from o in context.Orders.AsExpandable(optimizer) let myTemp = t == 1 ? o.Amount + 10 : t == 2 ? o.Amount - 10 : o.Amount select new { OrderDate = o.OrderDate, FixedAmount = myTemp }; var qry2 = from x in qry1 where x.FixedAmount < 100 select x; var res = qry2.ToList(); ``` -------------------------------- ### Call QueryCustomers with Purchase Price Criteria Source: https://github.com/scottksmith95/linqkit/blob/master/README.md Example usage of the QueryCustomers method with a lambda expression that filters purchases by price. This demonstrates how to pass dynamic criteria to retrieve customers who made purchases exceeding a specified threshold. ```csharp string[] bigSpenders = QueryCustomers (p => p.Price > 1000); ``` -------------------------------- ### SQL Output: Unoptimized LinqKit Query Source: https://github.com/scottksmith95/linqkit/blob/master/README.md Shows the SQL query generated from the C# example before applying expression optimization. Notice the use of CASE statements and dynamic parameters, which can hinder SQL Server's query plan caching. ```sql exec sp_executesql N' SELECT [Extent1].[Amount] AS [Amount], [Extent1].[OrderDate] AS [OrderDate], CASE WHEN (1 = @p__linq__0) THEN [Extent1].[Amount] + 10 WHEN (2 = @p__linq__1) THEN [Extent1].[Amount] - 10 ELSE [Extent1].[Amount] END AS [C1] FROM [dbo].[Orders] AS [Extent1] WHERE (CASE WHEN (1 = @p__linq__0) THEN [Extent1].[Amount] + 10 WHEN (2 = @p__linq__1) THEN [Extent1].[Amount] - 10 ELSE [Extent1].[Amount] END) < 100 ',N'@p__linq__0 int,@p__linq__1 int',@p__linq__0=2,@p__linq__1=2 ``` -------------------------------- ### Combine IsCurrent with Additional Predicate using LINQKit.And Source: https://github.com/scottksmith95/linqkit/blob/master/README.md This C# example demonstrates how to combine the reusable `IsCurrent` predicate with another condition using LINQKit's `And` method. It filters `db.PriceLists` for items that are currently valid AND whose 'Name' starts with 'A'. ```csharp var currentPriceLists = db.PriceLists.Where ( PriceList.IsCurrent().And (p => p.Name.StartsWith ("A"))); ``` -------------------------------- ### Create PriceList Table Schema Source: https://github.com/scottksmith95/linqkit/blob/master/README.md This SQL script defines the schema for a 'PriceList' table. It includes columns for ID, Name, ValidFrom, and ValidTo, with appropriate data types and constraints. This serves as an example for tables that might contain date validity information. ```sql create table PriceList ( ID int not null primary key, Name nvarchar(50) not null, ValidFrom datetime, ValidTo datetime ) ``` -------------------------------- ### Filter PriceLists by Current Validity (SQL Example) Source: https://github.com/scottksmith95/linqkit/blob/master/README.md This SQL query demonstrates how to select 'Name' from 'PriceLists' where the records are currently valid, considering 'ValidFrom' and 'ValidTo' columns. It handles cases where these date columns might be null. ```sql from p in PriceLists where (p.ValidFrom == null || p.ValidFrom <= DateTime.Now) && (p.ValidTo == null || p.ValidTo >= DateTime.Now) select p.Name ``` -------------------------------- ### C# Configuration: Static Expression Optimizer for LinqKit Source: https://github.com/scottksmith95/linqkit/blob/master/README.md Configures LinqKit to use the expression optimizer statically by assigning the `ExpressionOptimizer.visit` method to `LinqKitExtension.QueryOptimizer`. This should be done once at application startup. ```csharp LinqKitExtension.QueryOptimizer = ExpressionOptimizer.visit; ``` -------------------------------- ### Insert Demo Data into Orders Table Source: https://github.com/scottksmith95/linqkit/blob/master/README.md This SQL script inserts sample records into the 'Orders' table. It provides three rows with different 'Amount' and 'OrderDate' values to populate the database for testing queries. ```sql -- Insert some demo data: INSERT INTO [dbo].[Orders]([Amount],[OrderDate]) VALUES (3, '2016-01-01') INSERT INTO [dbo].[Orders]([Amount],[OrderDate]) VALUES (5, '2016-01-01') INSERT INTO [dbo].[Orders]([Amount],[OrderDate]) VALUES (7, '2016-01-02') GO ``` -------------------------------- ### Combine Product Predicates Using AND and OR Source: https://github.com/scottksmith95/linqkit/blob/master/README.md Demonstrates how to combine predefined and dynamically generated product predicates using AND and OR extension methods from PredicateBuilder. This allows for complex query construction. ```csharp var newKids = Product.ContainsInDescription ("BlackBerry", "iPhone"); var classics = Product.ContainsInDescription ("Nokia", "Ericsson") .And (Product.IsSelling()); var query = from p in Data.Products.Where (newKids.Or (classics)) select p; ``` -------------------------------- ### Dynamic Predicate Construction (All Keywords) Source: https://github.com/scottksmith95/linqkit/blob/master/README.md This C# code demonstrates using PredicateBuilder to dynamically construct an 'AND'-based predicate for searching products. It initializes a PredicateBuilder and iteratively adds 'Contains' conditions using the 'And' method. ```csharp IQueryable SearchProducts (params string[] keywords) { var predicate = PredicateBuilder.New(true); foreach (string keyword in keywords) { string temp = keyword; predicate = predicate.And (p => p.Description.Contains (temp)); } return dataContext.Products.Where (predicate); } ``` -------------------------------- ### Dynamic Predicate Construction (Any Keyword) Source: https://github.com/scottksmith95/linqkit/blob/master/README.md This C# code demonstrates using PredicateBuilder to dynamically construct an 'OR'-based predicate for searching products. It initializes a PredicateBuilder and iteratively adds 'Contains' conditions using the 'Or' method. ```csharp IQueryable SearchProducts (params string[] keywords) { var predicate = PredicateBuilder.New(); foreach (string keyword in keywords) { string temp = keyword; predicate = predicate.Or (p => p.Description.Contains (temp)); } return dataContext.Products.Where (predicate); } ``` -------------------------------- ### SQL Output: Optimized LinqKit Query (Static) Source: https://github.com/scottksmith95/linqkit/blob/master/README.md Illustrates the SQL query generated after applying the static expression optimizer. The dynamic parameters and CASE statements are resolved, resulting in a simpler query that is more amenable to SQL Server caching. ```sql SELECT [Extent1].[Amount] AS [Amount], [Extent1].[OrderDate] AS [OrderDate], [Extent1].[Amount] - 10 AS [C1] FROM [dbo].[Orders] AS [Extent1] WHERE ([Extent1].[Amount] - 10) < 100 ``` -------------------------------- ### Global Query Optimization Configuration using LinqKit and Expression Optimizer Source: https://context7.com/scottksmith95/linqkit/llms.txt Configures LinqKit to use Linq.Expression.Optimizer globally for all queries. This is typically done once at application startup. It optimizes dynamic parameters in LINQ expressions, leading to improved SQL query plan caching and database performance. Requires the 'Linq.Expression.Optimizer' NuGet package. ```csharp using System; using System.Linq; using LinqKit; using ExpressionOptimizer = LinqKit.LinqKitExtension; // Global configuration (call once at application startup) public class Startup { public void ConfigureServices() { // Enable optimization for all queries LinqKitExtension.QueryOptimizer = Linq.Expression.Optimizer.ExpressionOptimizer.visit; } } // Query with dynamic parameters that get optimized public IQueryable GetOrdersOptimized(MyDbContext context) { // Simulate dynamic non-database parameter var monthOffset = DateTime.Now.Month % 3; var query = from o in context.Orders.AsExpandable() let adjustedAmount = monthOffset == 1 ? o.Amount + 10 : monthOffset == 2 ? o.Amount - 10 : o.Amount select new { OrderDate = o.OrderDate, AdjustedAmount = adjustedAmount }; return query.Where(x => x.AdjustedAmount < 100); } // Without optimizer: // SQL: WHERE (CASE WHEN @p1 = 1 THEN Amount + 10 WHEN @p1 = 2 THEN Amount - 10 ELSE Amount END) < 100 // With optimizer: // SQL: WHERE (Amount - 10) < 100 -- parameters evaluated at compile time ``` -------------------------------- ### Basic Keyword Search (All Keywords) Source: https://github.com/scottksmith95/linqkit/blob/master/README.md This C# code snippet demonstrates a basic keyword search for products where the description must contain all specified keywords. It iterates through keywords, chaining 'Contains' calls. A temporary variable is used to avoid the outer variable trap in the foreach loop. ```csharp IQueryable SearchProducts (params string[] keywords) { IQueryable query = dataContext.Products; foreach (string keyword in keywords) { string temp = keyword; query = query.Where (p => p.Description.Contains (temp)); } return query; } ``` -------------------------------- ### Create Reusable Product Predicate: IsSelling Source: https://github.com/scottksmith95/linqkit/blob/master/README.md Defines a static method that returns an expression predicate to filter products that are currently selling and have had a recent sale. This promotes reusability in data access layers. ```csharp public partial class Product { public static Expression> IsSelling() { return p => !p.Discontinued && p.LastSale > DateTime.Now.AddDays (-30); } } ``` -------------------------------- ### Implement IValidFromTo Interface in Partial Classes Source: https://github.com/scottksmith95/linqkit/blob/master/README.md These C# snippets show how to implement the `IValidFromTo` interface in partial entity classes like `PriceList` and `Product`. This is necessary to use the generic `IsCurrent()` method, allowing these classes to be filtered by date validity. ```csharp public partial class PriceList : IValidFromTo { } public partial class Product : IValidFromTo { } ``` -------------------------------- ### Entity Framework MyDbContext Definition Source: https://github.com/scottksmith95/linqkit/blob/master/README.md This C# code defines a custom Entity Framework DbContext named 'MyDbContext'. It configures the connection string and exposes an 'Orders' DbSet. Database initialization is explicitly set to null, implying manual database management or migration. ```csharp using System.Data.Entity; /// Some simple EF DBContext item for this example public class MyDbContext : DbContext { static MyDbContext() { Database.SetInitializer(null); } public MyDbContext() : base( "Server=localhost;Database=MyDatabase;Integrated Security = True;"){} public DbSet Orders { get; set; } } ``` -------------------------------- ### Working Query on Purchases Table Directly Source: https://github.com/scottksmith95/linqkit/blob/master/README.md Demonstrates that calling Any() directly on the Purchases table works because Table implements IQueryable<>, allowing the Queryable.Any() overload that accepts Expression> to be used without compilation errors. ```csharp bool any = data.Purchases.Any(purchaseCriteria); ``` -------------------------------- ### Query Customers with AsExpandable Solution - LINQKit Source: https://github.com/scottksmith95/linqkit/blob/master/README.md Provides the LINQKit solution to plug expressions into EntitySets/EntityCollections by calling AsExpandable() on the Table<> object and Compile() on the expression variable when used on an EntitySet or EntityCollection. This enables proper expression tree conversion for LINQ to SQL and Entity Framework. ```csharp static string[] QueryCustomers (Expression> purchaseCriteria) { var data = new MyDataContext(); var query = from c in data.Customers.AsExpandable() where c.Purchases.Any (purchaseCriteria.Compile()) select c.Name; return query.ToArray(); } ``` -------------------------------- ### Create Orders Table Schema with Primary Key Source: https://github.com/scottksmith95/linqkit/blob/master/README.md This SQL script creates an 'Orders' table in a SQL Server database. It defines columns for 'Id' (auto-incrementing primary key), 'Amount', and 'OrderDate', setting up the necessary structure for sample data insertion. ```sql CREATE TABLE [dbo].[Orders]( Id int NOT NULL IDENTITY (1, 1), Amount int NOT NULL, OrderDate smalldatetime NOT NULL ) ON [PRIMARY] GO ALTER TABLE [dbo].[Orders] ADD CONSTRAINT PK_Table_1 PRIMARY KEY CLUSTERED (Id) WITH(STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] GO ``` -------------------------------- ### Query Customers Method Implementation Problem Source: https://github.com/scottksmith95/linqkit/blob/master/README.md Shows the problematic implementation of QueryCustomers that attempts to use an Expression> with EntitySet.Any(). This code fails to compile because EntitySet<> and EntityCollection<> do not implement IQueryable<>, preventing the use of Queryable's Any method that accepts Expression>. ```csharp static string[] QueryCustomers (Expression> purchaseCriteria) { var data = new MyDataContext(); // or MyObjectContext() var query = from c in data.Customers where c.Purchases.Any(purchaseCriteria) // will not compile select c.Name; return query.ToArray(); } ``` -------------------------------- ### Combining Expressions with Invoke and Expand (LINQKit) Source: https://github.com/scottksmith95/linqkit/blob/master/README.md This C# code illustrates how to combine multiple LINQ expression trees using LINQKit's Invoke and Expand methods. Invoke is used to call one expression from another, and Expand is used to flatten the combined expression tree into a single, usable expression. This is particularly useful for building complex query predicates. ```csharp Expression> criteria1 = p => p.Price > 1000; Expression> criteria2 = p => criteria1.Invoke (p) || p.Description.Contains ("a"); Console.WriteLine (criteria2.Expand().ToString()); ``` -------------------------------- ### Query Customers with Purchase Criteria - Method Signature Source: https://github.com/scottksmith95/linqkit/blob/master/README.md Demonstrates the method signature for QueryCustomers that accepts an Expression> parameter to filter purchases based on custom criteria. This pattern is essential for LINQ to SQL and Entity Framework queries where the criteria needs to be an expression tree rather than a compiled delegate. ```csharp static string[] QueryCustomers (Expression> purchaseCriteria) { ... } ``` -------------------------------- ### Per-Query Optimization using LinqKit and Expression Optimizer Source: https://context7.com/scottksmith95/linqkit/llms.txt Applies Linq.Expression.Optimizer to a specific LINQ query using LinqKit's `AsExpandable()` method with a custom optimizer delegate. This allows for granular control over optimization for individual queries, suitable when global configuration is not desired or feasible. It helps reduce SQL parameter variations for better query plan reuse. ```csharp // Per-query optimization (alternative to global config) using (var context = new MyDbContext()) { var optimizer = Linq.Expression.Optimizer.ExpressionOptimizer.visit; var monthOffset = DateTime.Now.Month % 3; var query = from o in context.Orders.AsExpandable(optimizer) let myTemp = monthOffset == 1 ? o.Amount + 10 : monthOffset == 2 ? o.Amount - 10 : o.Amount where myTemp > 50 select new { o.OrderDate, AdjustedAmount = myTemp }; var results = query.ToList(); // Optimized SQL with fewer parameters for better query plan reuse } ``` -------------------------------- ### Create Dynamic Product Predicate: ContainsInDescription Source: https://github.com/scottksmith95/linqkit/blob/master/README.md Generates an expression predicate dynamically to filter products whose description contains any of the specified keywords. It utilizes PredicateBuilder to combine multiple OR conditions. ```csharp public partial class Product { public static Expression> ContainsInDescription (params string[] keywords) { var predicate = PredicateBuilder.New(); foreach (string keyword in keywords) { string temp = keyword; predicate = predicate.Or (p => p.Description.Contains (temp)); } return predicate; } } ``` -------------------------------- ### Dynamic Predicate Construction with PredicateBuilder.New() in C# Source: https://context7.com/scottksmith95/linqkit/llms.txt Creates an ExpressionStarter for building complex predicates dynamically using And/Or operators. This is essential for scenarios where filter conditions are determined at runtime. It accepts a generic type T for the entity and returns an Ilinq to create dynamic queries. ```csharp using System.Linq; using LinqKit; // Dynamic search with multiple keywords (OR logic) public IQueryable SearchProducts(params string[] keywords) { using (var context = new MyDbContext()) { var predicate = PredicateBuilder.New(); foreach (string keyword in keywords) { string temp = keyword; predicate = predicate.Or(p => p.Description.Contains(temp)); } return context.Products.AsExpandable().Where(predicate); } } // Usage: Search for products containing any keyword var results = SearchProducts("laptop", "tablet", "phone").ToList(); // SQL: SELECT * FROM Products WHERE Description LIKE '%laptop%' OR Description LIKE '%tablet%' OR Description LIKE '%phone%' // Dynamic filter with multiple conditions (AND logic) public IQueryable FilterProducts(decimal? minPrice, decimal? maxPrice, bool? inStock) { using (var context = new MyDbContext()) { var predicate = PredicateBuilder.New(true); if (minPrice.HasValue) predicate = predicate.And(p => p.Price >= minPrice.Value); if (maxPrice.HasValue) predicate = predicate.And(p => p.Price <= maxPrice.Value); if (inStock.HasValue) predicate = predicate.And(p => p.InStock == inStock.Value); return context.Products.AsExpandable().Where(predicate); } } // Usage: Filter with optional conditions var filtered = FilterProducts(minPrice: 100, maxPrice: 500, inStock: true).ToList(); // SQL: SELECT * FROM Products WHERE Price >= 100 AND Price <= 500 AND InStock = 1 ``` -------------------------------- ### Using AsExpandable with PredicateBuilder (LINQKit) Source: https://github.com/scottksmith95/linqkit/blob/master/README.md This C# code snippet highlights the requirement to call AsExpandable() on the initial data source (e.g., a table) when using expressions built with PredicateBuilder in conjunction with Entity Framework. This ensures that the dynamically built predicates are correctly processed by the query provider. ```csharp // Assuming 'data' is your DbContext and 'Purchases' is a DbSet // and 'predicate' is an Expression> built using PredicateBuilder var query = data.Purchases.AsExpandable().Where(predicate); ``` -------------------------------- ### Entity Framework Order Model Definition Source: https://github.com/scottksmith95/linqkit/blob/master/README.md This C# code defines the 'Order' entity class, mapping it to a database table using Entity Framework conventions and attributes. It includes properties for 'Id', 'Amount', and 'OrderDate', with appropriate data types and validation attributes. ```csharp using System.ComponentModel.DataAnnotations; public class Order { [Key] public int Id { get; set; } [Required] public int Amount { get; set; } [Required] public DateTime OrderDate { get; set; } } ``` -------------------------------- ### Refine Product Predicate: IsSelling with MinPurchases Source: https://github.com/scottksmith95/linqkit/blob/master/README.md Extends the IsSelling predicate to include a minimum purchase count criterion. It references association properties (Purchases) to perform a subquery-like filtering. ```csharp public static Expression> IsSelling (int minPurchases) { return prod => !prod.Discontinued && prod.Purchases.Where (purch => purch.Date > DateTime.Now.AddDays(-30)) .Count() >= minPurchases; } ``` -------------------------------- ### Combine LINQ Predicates with And/Or using PredicateBuilder Source: https://context7.com/scottksmith95/linqkit/llms.txt Demonstrates how to combine multiple Expression> predicates using logical AND and OR operators. This is useful for building dynamic WHERE clauses in LINQ queries. Requires the LinqKit library. ```csharp using System; using System.Linq.Expressions; using LinqKit; // Define reusable predicates public static class ProductPredicates { public static Expression> IsExpensive() { return p => p.Price > 1000; } public static Expression> IsInStock() { return p => p.InStock && p.Quantity > 0; } public static Expression> IsFeatured() { return p => p.Featured; } } // Combine predicates with And var expensiveInStock = ProductPredicates.IsExpensive() .And(ProductPredicates.IsInStock()); // Usage in a DbContext query // using (var context = new MyDbContext()) // { // var products = context.Products.AsExpandable() // .Where(expensiveInStock) // .ToList(); // // SQL: SELECT * FROM Products WHERE Price > 1000 AND InStock = 1 AND Quantity > 0 // } // Combine predicates with Or var featuredOrExpensive = ProductPredicates.IsFeatured() .Or(ProductPredicates.IsExpensive()); // Usage in a DbContext query // using (var context = new MyDbContext()) // { // var products = context.Products.AsExpandable() // .Where(featuredOrExpensive) // .ToList(); // // SQL: SELECT * FROM Products WHERE Featured = 1 OR Price > 1000 // } ``` -------------------------------- ### Query Customers with Expression in Subquery (LINQKit) Source: https://github.com/scottksmith95/linqkit/blob/master/README.md This C# code demonstrates how to query customers based on a purchase criteria using an expression within a subquery. By calling AsExpandable() on the Customers data source, LINQKit correctly handles the expression reference within the subquery, which would otherwise cause an error in LINQ to SQL. ```csharp static string[] QueryCustomers (Expression> purchaseCriteria) { var data = new MyDataContext(); var query = from c in data.Customers.AsExpandable() let custPurchases = data.Purchases.Where (p => p.CustomerID == c.ID) where custPurchases.Any (purchaseCriteria) select c.Name; return query.ToArray(); } ``` -------------------------------- ### Dynamically Build Nested Predicates with PredicateBuilder Source: https://github.com/scottksmith95/linqkit/blob/master/README.md Illustrates how to dynamically construct a complex predicate involving nested AND and OR conditions. It shows building inner (parenthesized) expressions first and then incorporating them into outer expressions. ```csharp var inner = PredicateBuilder.New(); inner = inner.Start(p => p.Description.Contains ("foo")); inner = inner.Or(p => p.Description.Contains ("far")); var outer = PredicateBuilder.New(); outer = outer.Start(p => p.Price > 100); outer = outer.And(p => p.Price < 1000); outer = outer.And(inner); ``` -------------------------------- ### Manually Expand Expression Trees with LinqKit Source: https://context7.com/scottksmith95/linqkit/llms.txt Illustrates how to manually expand an expression tree using LinqKit's Expand() method. This replaces Invoke calls with their expression bodies, useful for inspecting or compiling expressions outside of a query context. Can also be used within queries as an alternative to AsExpandable(). ```csharp using System; using System.Linq.Expressions; using LinqKit; // Define expressions Expression> criteria1 = p => p.Price > 1000; Expression> criteria2 = p => criteria1.Invoke(p) || p.Description.Contains("premium"); // Expand manually to inspect the resulting expression tree var expanded = criteria2.Expand(); // Console.WriteLine(expanded.ToString()); // Output: p => ((p.Price > 1000) || p.Description.Contains("premium")) // Use Expand() within a query (alternative to AsExpandable) // using (var context = new MyDbContext()) // { // var products = context.Products.Where(criteria2.Expand()).ToList(); // // SQL: SELECT * FROM Products WHERE Price > 1000 OR Description LIKE '%premium%' // } // Expand and compile for direct execution var compiledFunc = criteria2.Expand().Compile(); // var product = new Product { Price = 1500, Description = "Standard" }; // bool matches = compiledFunc(product); // Returns: true ``` -------------------------------- ### Enable Expression Expansion with AsExpandable() in C# Source: https://context7.com/scottksmith95/linqkit/llms.txt Wraps an IQueryable to automatically expand expressions before Entity Framework processes them. This is required for using expression variables in subqueries or with PredicateBuilder. It takes an IQueryable as input and returns an IQueryable with expanded expressions, suitable for complex LINQ queries. ```csharp using System; using System.Linq; using System.Linq.Expressions; using LinqKit; // Basic usage with Entity Framework public string[] GetCustomerNames(Expression> purchaseCriteria) { using (var context = new MyDbContext()) { var query = from c in context.Customers.AsExpandable() where c.Purchases.Any(purchaseCriteria.Compile()) select c.Name; return query.ToArray(); } } // Usage example var bigSpenders = GetCustomerNames(p => p.Price > 1000); // Returns: ["Alice", "Bob", "Charlie"] ``` -------------------------------- ### Compose Expressions using Invoke for Dynamic Queries Source: https://context7.com/scottksmith95/linqkit/llms.txt Shows how to invoke one expression from within another using LinqKit's Invoke method. This allows for modular and reusable expression logic within complex LINQ queries. Requires LinqKit and must be used with Expand() or AsExpandable(). ```csharp using System; using System.Linq; using System.Linq.Expressions; using LinqKit; // Define base expressions Expression> isExpensive = p => p.Price > 1000; Expression> hasDiscount = p => p.DiscountPercent > 0; // Compose expressions using Invoke Expression> isExpensiveWithDiscount = p => isExpensive.Invoke(p) && hasDiscount.Invoke(p); // Use in query with AsExpandable // using (var context = new MyDbContext()) // { // var products = context.Products.AsExpandable() // .Where(isExpensiveWithDiscount) // .ToList(); // // SQL: SELECT * FROM Products WHERE Price > 1000 AND DiscountPercent > 0 // } // Multi-level composition example Expression> descriptionContainsA = p => p.Description.Contains("wireless"); Expression> complexFilter = p => isExpensive.Invoke(p) || descriptionContainsA.Invoke(p); // Use in query with AsExpandable // using (var context = new MyDbContext()) // { // var results = context.Products.AsExpandable() // .Where(complexFilter) // .ToList(); // // SQL: SELECT * FROM Products WHERE Price > 1000 OR Description LIKE '%wireless%' // } ``` -------------------------------- ### Entity Framework Integration for Predicates Source: https://github.com/scottksmith95/linqkit/blob/master/README.md This C# snippet shows how to adapt the PredicateBuilder usage for Entity Framework. It requires calling '.AsExpandable()' on the query to enable LINQKit's expression visitor to translate invocation expressions. ```csharp return objectContext.Products.AsExpandable().Where (predicate); ``` -------------------------------- ### C# Expression Variables in Subqueries Source: https://context7.com/scottksmith95/linqkit/llms.txt Enables the use of expression parameters within LINQ let clauses and subqueries, overcoming limitations often encountered with LINQ to SQL or Entity Framework. This allows for more complex and dynamic query constructions. ```csharp using System; using System.Linq; using System.Linq.Expressions; using LinqKit; // Assuming Customer, Purchase, Order, CustomerSummary, and MyDbContext are defined elsewhere. // Example placeholder definitions: // public class Customer { public int Id { get; set; } public string Name { get; set; } } // public class Purchase { public int CustomerId { get; set; } public decimal Amount { get; set; } } // public class Order { public int CustomerId { get; set; } public DateTime OrderDate { get; set; } public decimal Amount { get; set; } } // public class CustomerSummary { public string CustomerName { get; set; } public int OrderCount { get; set; } public decimal TotalAmount { get; set; } } // public class MyDbContext : IDisposable { public IQueryable Customers { get; set; } public IQueryable Purchases { get; set; } public IQueryable Orders { get; set; } public void Dispose() { } } // Query with expression in subquery public static string[] QueryCustomersWithCriteria( Expression> purchaseCriteria) { // using (var context = new MyDbContext()) // { // var query = from c in context.Customers.AsExpandable() // let custPurchases = context.Purchases // .Where(p => p.CustomerId == c.Id) // where custPurchases.Any(purchaseCriteria) // select c.Name; // return query.ToArray(); // } return new string[0]; // Placeholder return } // Usage: Find customers with high-value purchases // var richCustomers = QueryCustomersWithCriteria(p => p.Amount > 5000); // SQL: SELECT c.Name FROM Customers c // WHERE EXISTS (SELECT 1 FROM Purchases p // WHERE p.CustomerId = c.Id AND p.Amount > 5000) // Complex subquery with aggregation public static IQueryable GetCustomerSummaries( Expression> orderFilter) { // using (var context = new MyDbContext()) // { // var query = from c in context.Customers.AsExpandable() // let filteredOrders = context.Orders // .Where(o => o.CustomerId == c.Id) // .Where(orderFilter) // select new CustomerSummary // { // CustomerName = c.Name, // OrderCount = filteredOrders.Count(), // TotalAmount = filteredOrders.Sum(o => o.Amount) // }; // return query; // } return Enumerable.Empty().AsQueryable(); // Placeholder return } // Usage: Get summaries for recent orders // var recentDate = DateTime.Now.AddMonths(-3); // var summaries = GetCustomerSummaries(o => o.OrderDate > recentDate).ToList(); // Returns: [{ CustomerName = "Alice", OrderCount = 5, TotalAmount = 2500 }, ...] ``` -------------------------------- ### Query Customers with Expression in Subquery (Without LINQKit) Source: https://github.com/scottksmith95/linqkit/blob/master/README.md This C# code represents a query attempting to use an expression within a subquery without the aid of LINQKit. This pattern typically fails with LINQ to SQL due to its inability to handle expression references in subqueries, resulting in an 'Unsupported overload' exception. ```csharp static string[] QueryCustomers (Expression> purchaseCriteria) { var data = new MyDataContext(); var query = from c in data.Customers let custPurchases = data.Purchases.Where (p => p.CustomerID == c.ID) where custPurchases.Any (purchaseCriteria) select c.Name; return query.ToArray(); } ``` -------------------------------- ### C# Generic Predicates with Interface Constraints Source: https://context7.com/scottksmith95/linqkit/llms.txt Creates reusable predicates applicable to multiple entity types by leveraging interface constraints. This allows defining predicate logic once and applying it to any entity that implements a specified interface, such as IValidFromTo for temporal data. ```csharp using System; using System.Linq; using System.Linq.Expressions; using LinqKit; // Define interface for temporal entities public interface IValidFromTo { DateTime? ValidFrom { get; } DateTime? ValidTo { get; } } // Generic predicate for current records public static class TemporalPredicates { public static Expression> IsCurrent() where TEntity : IValidFromTo { return e => (e.ValidFrom == null || e.ValidFrom <= DateTime.Now) && (e.ValidTo == null || e.ValidTo >= DateTime.Now); } public static Expression> WasActiveOn(DateTime date) where TEntity : IValidFromTo { return e => (e.ValidFrom == null || e.ValidFrom <= date) && (e.ValidTo == null || e.ValidTo >= date); } } // Implement interface in entity classes public partial class PriceList : IValidFromTo { public int Id { get; set; } public string Name { get; set; } public DateTime? ValidFrom { get; set; } public DateTime? ValidTo { get; set; } } public partial class Product : IValidFromTo { public int Id { get; set; } public string Name { get; set; } public DateTime? ValidFrom { get; set; } public DateTime? ValidTo { get; set; } } // Use with different entity types // Assuming MyDbContext is a DbContext class // using (var context = new MyDbContext()) // { // // Get current price lists // var currentPriceLists = context.PriceLists // .AsExpandable() // .Where(TemporalPredicates.IsCurrent()) // .ToList(); // // SQL: SELECT * FROM PriceLists WHERE (ValidFrom IS NULL OR ValidFrom <= GETDATE()) // // AND (ValidTo IS NULL OR ValidTo >= GETDATE()) // // Get current products // var currentProducts = context.Products // .AsExpandable() // .Where(TemporalPredicates.IsCurrent()) // .ToList(); // // Get products active on specific date // var historicalDate = new DateTime(2023, 1, 1); // var historicalProducts = context.Products // .AsExpandable() // .Where(TemporalPredicates.WasActiveOn(historicalDate)) // .ToList(); // // Combine with other predicates // var currentPremiumProducts = TemporalPredicates.IsCurrent() // .And(p => p.Name.StartsWith("Premium")); // var results = context.Products.AsExpandable() // .Where(currentPremiumProducts) // .ToList(); // } ``` -------------------------------- ### Define Reusable IsCurrent Predicate for PriceList Source: https://github.com/scottksmith95/linqkit/blob/master/README.md This C# code defines a static method `IsCurrent` within the `PriceList` class that returns an `Expression>`. This expression represents the logic to filter `PriceList` objects that are currently valid based on their `ValidFrom` and `ValidTo` dates. ```csharp public static Expression> IsCurrent() { return p => (p.ValidFrom == null || p.ValidFrom <= DateTime.Now) && (p.ValidTo == null || p.ValidTo >= DateTime.Now); } ``` -------------------------------- ### C# Reusable Predicates with LinqKit Source: https://context7.com/scottksmith95/linqkit/llms.txt Defines and utilizes reusable predicate methods in C# using LinqKit. These methods encapsulate business logic and can be combined using logical operators like OR and AND for complex query construction. The pattern promotes a clean data access layer. ```csharp using System; using System.Linq; using System.Linq.Expressions; using LinqKit; // Define reusable predicates as static methods on entity class public partial class Product { public static Expression> IsSelling() { return p => !p.Discontinued && p.LastSale > DateTime.Now.AddDays(-30); } public static Expression> IsSelling(int minPurchases) { return p => !p.Discontinued && p.Purchases.Where(purch => purch.Date > DateTime.Now.AddDays(-30)) .Count() >= minPurchases; } public static Expression> ContainsInDescription(params string[] keywords) { var predicate = PredicateBuilder.New(); foreach (string keyword in keywords) { string temp = keyword; predicate = predicate.Or(p => p.Description.Contains(temp)); } return predicate; } public static Expression> InPriceRange(decimal min, decimal max) { return p => p.Price >= min && p.Price <= max; } } // Use predicates in queries using (var context = new MyDbContext()) { // Simple usage var sellingProducts = context.Products.AsExpandable() .Where(Product.IsSelling()) .ToList(); // Combine multiple predicates var newKids = Product.ContainsInDescription("iPhone", "Samsung"); var classics = Product.ContainsInDescription("Nokia", "Motorola") .And(Product.IsSelling()); var query = context.Products.AsExpandable() .Where(newKids.Or(classics)) .ToList(); // Complex composition var premiumSelling = Product.IsSelling(minPurchases: 10) .And(Product.InPriceRange(500, 2000)) .And(Product.ContainsInDescription("wireless", "pro")); var results = context.Products.AsExpandable() .Where(premiumSelling) .OrderByDescending(p => p.Price) .Take(20) .ToList(); // SQL: SELECT TOP 20 * FROM Products // WHERE (NOT Discontinued AND [...sales logic...] >= 10) // AND (Price >= 500 AND Price <= 2000) // AND (Description LIKE '%wireless%' OR Description LIKE '%pro%') // ORDER BY Price DESC } ``` -------------------------------- ### Build Nested C# Predicates with LinqKit PredicateBuilder Source: https://context7.com/scottksmith95/linqkit/llms.txt Constructs complex, nested query predicates by first building inner predicates and then combining them with outer predicates using AND and OR logic. This method is useful for creating dynamic WHERE clauses in LINQ queries, especially when dealing with multiple, potentially complex conditions. It requires the LinqKit library and a DbContext. ```csharp using System.Linq; using LinqKit; // Build nested predicate: (Price > 100 AND Price < 1000) AND (Description contains "foo" OR Description contains "bar") public IQueryable ComplexSearch(MyDbContext context) { // Build inner predicate with OR logic var inner = PredicateBuilder.New(); inner = inner.Start(p => p.Description.Contains("foo")); inner = inner.Or(p => p.Description.Contains("bar")); // Build outer predicate with AND logic var outer = PredicateBuilder.New(); outer = outer.Start(p => p.Price > 100); outer = outer.And(p => p.Price < 1000); outer = outer.And(inner); return context.Products.AsExpandable().Where(outer); } // Usage using (var context = new MyDbContext()) { var results = ComplexSearch(context).ToList(); // SQL: SELECT * FROM Products // WHERE Price > 100 AND Price < 1000 // AND (Description LIKE '%foo%' OR Description LIKE '%bar%') } // Advanced nested example with multiple levels public IQueryable AdvancedFilter(MyDbContext context, string[] brands, string[] categories) { // Brand filter (OR) var brandPredicate = PredicateBuilder.New(); foreach (var brand in brands) { string temp = brand; brandPredicate = brandPredicate.Or(p => p.Brand == temp); } // Category filter (OR) var categoryPredicate = PredicateBuilder.New(); foreach (var category in categories) { string temp = category; categoryPredicate = categoryPredicate.Or(p => p.Category == temp); } // Combine: (brand1 OR brand2) AND (cat1 OR cat2) AND inStock var finalPredicate = PredicateBuilder.New(); finalPredicate = finalPredicate.Start(brandPredicate); finalPredicate = finalPredicate.And(categoryPredicate); finalPredicate = finalPredicate.And(p => p.InStock); return context.Products.AsExpandable().Where(finalPredicate); } ``` -------------------------------- ### Use Generic IsCurrent Predicate with LINQKit Source: https://github.com/scottksmith95/linqkit/blob/master/README.md This C# code shows how to use the generic `IsCurrent` predicate with LINQKit's `Where` clause. It assumes `db.PriceLists` is an `IQueryable` source. The `PriceList.IsCurrent()` expression is passed to the `Where` method for filtering. ```csharp var currentPriceLists = db.PriceLists.Where (PriceList.IsCurrent()); ``` -------------------------------- ### Define Generic IsCurrent Predicate with Interface Constraint Source: https://github.com/scottksmith95/linqkit/blob/master/README.md This C# code defines a generic static method `IsCurrent` that returns an `Expression>`. It constrains `TEntity` to implement the `IValidFromTo` interface, ensuring entities have `ValidFrom` and `ValidTo` properties. This allows for reusable date validity filtering across different entity types. ```csharp public interface IValidFromTo { DateTime? ValidFrom { get; } DateTime? ValidTo { get; } } public static Expression> IsCurrent() where TEntity : IValidFromTo { return e => (e.ValidFrom == null || e.ValidFrom <= DateTime.Now) && (e.ValidTo == null || e.ValidTo >= DateTime.Now); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.