Sorting
MapCrud allows API consumers to sort the results of GET requests based on any public property of the entity. This provides flexibility in how data is presented and consumed.
Sorting is controlled by the sortBy query parameter.
How to Use
When an entity is mapped using app.MapCrud<TEntity>(), sorting capabilities are automatically available on the endpoint that retrieves multiple entities (e.g., GET /your-entity-route).
- To sort by a property in ascending order, use the property name directly (e.g.,
sortBy=name). - To sort by a property in descending order, prefix the property name with a hyphen (
-) (e.g.,sortBy=-price).
Example Model
Let's use the same Product model:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public int StockQuantity { get; set; }
}
Mapped as:
app.MapCrud<Product>("/products");
Requesting Sorted Data
Clients can request sorted data by including the sortBy query parameter.
Example 1: Get all products sorted by Name in ascending order
curl "http://localhost:5000/products?sortBy=Name"
URL: http://localhost:5000/products?sortBy=Name
Example 2: Get all products sorted by Price in descending order
curl "http://localhost:5000/products?sortBy=-Price"
URL: http://localhost:5000/products?sortBy=-Price
Example 3: Get all products sorted by StockQuantity in ascending order
curl "http://localhost:5000/products?sortBy=StockQuantity"
URL: http://localhost:5000/products?sortBy=StockQuantity
Note on Case Sensitivity: Property names for sortBy are typically case-insensitive, but this might depend on the underlying query provider or database collation if you are using one (like Entity Framework Core). It's good practice to match the case of the property in your model.
OpenAPI (Swagger) Behavior
The sortBy query parameter will be automatically included in the OpenAPI documentation for the relevant GET endpoints.
When viewing the API documentation via Swagger UI for the GET /products endpoint, you would see:
sortBy(string, query): The property name to sort by. Prefix with '-' for descending order (e.g.,nameor-price).
This clearly communicates the sorting capabilities to API consumers. If multiple sortBy parameters are provided, the behavior might depend on the underlying repository implementation (e.g., some might support multi-column sorting, others might only use the first one). MapCrud's default behavior is to support sorting by a single field.