background preloader

C# 6.0 in a Nutshell - PredicateBuilder

C# 6.0 in a Nutshell - PredicateBuilder
Dynamically Composing Expression Predicates Suppose you want to write a LINQ to SQL or Entity Framework query that implements a keyword-style search. In other words, a query that returns rows whose description contains some or all of a given set of keywords. We can proceed as follows: IQueryable<Product> SearchProducts (params string[] keywords) { IQueryable<Product> query = dataContext.Products; foreach (string keyword in keywords) { string temp = keyword; query = query.Where (p => p.Description.Contains (temp)); } return query; } The temporary variable in the loop is required to avoid the outer variable trap, where the same variable is captured for each iteration of the foreach loop. So far, so good. Of all the things that will drive you to manually constructing expression trees, the need for dynamic predicates is the most common in a typical business application. Using PredicateBuilder Here's how to solve the preceding example with PredicateBuilder: PredicateBuilder Source Code How it Works

Dynamic query SQL queries in LINQ Translating SQL to LINQ can prove difficult for new and experienced C# developers. This post contains common SQL queries written in LINQ. I hope it’ll serve as a reference when writing LINQ queries. I’ll use a MS SQL database and Entity Framework for my examples. However, these examples can be extracted to other ORMs and databases. Also, consider reading why LINQ beats SQL to learn how to think in LINQ terms rather than translating SQL to LINQ. Data model We’ll use a simple data model that contains books and authors for our examples. Entity Framework data context SELECT * FROM books IQueryable<Book> books = db.Books; SELECT TOP 1 * FROM books //There are many ways to select the first row from a query. single column SELECT title FROM books //fluent syntaxIQueryable<string> titles = db.Books.Select(b => b.Title); //query syntaxIQueryable<string> titles2 = from b in db.Books select b.Title; multiple columns SELECT title, numPages FROM books single condition SELECT * FROM books WHERE title = 'Catch 22'

Related: