-
Notifications
You must be signed in to change notification settings - Fork 3
Dynamic Sorting
Adam O'Neil edited this page Oct 26, 2020
·
1 revision
To make the ORDER BY clause dynamic in a Dapper.QX query, use the [OrderBy]
attribute on a query property along with the {orderBy} token within your SQL. Create an enum to use with your custom ORDER BY property. For example:
public enum MySortOptions
{
LastName,
OrderDate,
OrderAmount
}
public class MyOrderQuery : Query<OrderResult>
{
public MyOrderQuery() : base("SELECT * FROM [dbo].[Orders] [o] ORDER BY {orderBy}")
[OrderBy(MySortOptions.LastName, "[o].[LastName] ASC")]
[OrderBy(MySortOptions.OrderDate, "[o].[OrderDate] DESC")]
[OrderBy(MySortOptions.OrderAmount, "(SELECT SUM([Amount]) FROM [dbo].[OrderItems] WHERE [OrderId]=[o].[Id]) DESC")]
public MySortOptions Sort { get; set; }
}
Then, you would set this Sort
property like any other when executing:
var results = new MyOrderQuery() { Sort = MySortOptions.OrderDate }.ExecuteAsync(GetConnection);
Note this example uses a subquery within the ORDER BY clause. Sorting by a subquery result may not perform very well, but the point of the example is to show you can use any valid SQL with your [OrderBy]
usage.