Skip to content
pagebrooks edited this page Dec 6, 2011 · 22 revisions

The predicate system in Dapper Extensions is very simple to use. In the examples below we will use the following model:

public class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public bool Active { get; set; }
    public DateTime DateCreated { get; set; }
}

Simple FieldPredicate Operation

To create a simple predicate, just create a FieldPredicate and pass it to the query operation. FieldPredicate expects a generic type which allows for strong typing.

In the example below, we are returning all Persons where the Active value is equal to true.

Code

using (SqlConnection cn = new SqlConnection(_connectionString))
{
    cn.Open();
    var predicate = Predicates.Field<Person>(f => f.Active, Operator.Eq, true);
    IEnumerable<Person> list = cn.GetList<Person>(predicate);
    cn.Close();
}

Generated SQL

SELECT 
   [Person].[Id]
 , [Person].[FirstName]
 , [Person].[LastName]
 , [Person].[Active]
 , [Person].[DateCreated] 
FROM [Person]
WHERE ([Person].[Active] = @Activep0)

Compound Predicate (Predicate Group)

Compound predicates are achieved through the use of predicate groups. For each predicate group, you must choose an operator (AND/OR). Each predicate that is added to the group will be joined with the specified operator.

Multiple predicate groups can be joined together since each predicate group implements IPredicate.

In the example below, we create a predicate group with an AND operator:

Code

using (SqlConnection cn = new SqlConnection(_connectionString))
{
    cn.Open();
    var pg = new PredicateGroup { Operator = GroupOperator.And, Predicates = new List<IPredicate>() };
    pg.Predicates.Add(Predicates.Field<Person>(f => f.Active, Operator.Eq, true));
    pg.Predicates.Add(Predicates.Field<Person>(f => f.LastName, Operator.Like, "Br%"));
    IEnumerable<Person> list = cn.GetList<Person>(pg);
    cn.Close();
}

Generated SQL

SELECT 
   [Person].[Id]
 , [Person].[FirstName]
 , [Person].[LastName]
 , [Person].[Active]
 , [Person].[DateCreated] 
FROM [Person] 
WHERE (([Person].[Active] = @Activep0) 
      AND ([Person].[LastName] LIKE @LastNamep1))
Clone this wiki locally