Before you start using DateOnly
and TimeOnly
in your Dapper queries or commands, you need to register the type handlers. This is a one-time setup that should be called before any database operation.
using HamedStack.Dapper;
// Register type handlers at the start of the application
SqlMapperTypeHandler.AddDateOnlyTimeOnlyTypeHandlers();
Once the type handlers are registered, you can use DateOnly
and TimeOnly
types directly in your Dapper queries as parameters or for mapping results.
using Dapper;
using System.Data.SqlClient;
string connectionString = "your_connection_string";
using var connection = new SqlConnection(connectionString);
connection.Open();
var date = new DateOnly(2023, 10, 05); // DateOnly value
var time = new TimeOnly(14, 30, 0); // TimeOnly value
string sql = "INSERT INTO YourTable (DateColumn, TimeColumn) VALUES (@Date, @Time)";
connection.Execute(sql, new { Date = date, Time = time });
string query = "SELECT DateColumn, TimeColumn FROM YourTable WHERE Id = @Id";
var result = connection.QuerySingleOrDefault(query, new { Id = 1 });
DateOnly dateResult = result.DateColumn;
TimeOnly timeResult = result.TimeColumn;