Skip to content

In a Nutshell

Adam O'Neil edited this page Dec 11, 2019 · 18 revisions

Dapper.QX revolves around the Query<TResult> class. Use this to encapsulate a SQL statement along with its available parameters. Here's a very simple case.

public class EmployeesResult
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime HireDate { get; set; }
}

public class Employees : Query<EmployeesResult>
{
    public Employees() : base("SELECT * FROM [dbo].[Employee] {where} ORDER BY [LastName], [FirstName]")

    [Where("[HireDate]>=@minHireDate")]
    public DateTime? MinHireDate { get; set; }

    [Where("[HireDate]<=@maxHireDate")]
    public DateTime? MaxHireDate { get; set; }
}

Use a query like this:

using (var cn = GetConnection())
{
    var results = await new Employees() { MinHireDate = new DateTime(2019, 1, 1) }.ExecuteAsync(cn);
}

Key points:

  • Use a Query<TResult> class to define your queries, passing the SQL in the constructor.
  • Use {where} or {andWhere} within your SQL to indicate where criteria is injected.
  • Add properties to your query class that correspond to parameters in the query. Implement optional criteria as nullable properties decorated with the [Where] or [Case] attributes. There's more you can do with properties, but these are good starting point.

Clone this wiki locally