This project demonstrates a common problem when using Dapper with DateTime values: database datetime columns do not preserve the DateTimeKind, so values stored as UTC come back with Kind = Unspecified. The solution implements a custom SqlMapper.TypeHandler<DateTime> called DateTimeHandler that automatically converts retrieved DateTime values to UTC kind using DateTime.SpecifyKind.
The code connects to a MySQL database, inserts a DateTime.UtcNow value, retrieves it through the custom type handler, and uses xUnit assertions to verify that the returned DateTime has DateTimeKind.Utc. It also tests DateTimeOffset compatibility. This is a practical pattern that any developer working with Dapper and timezone-sensitive data should be aware of, as it prevents subtle bugs caused by unspecified DateTime kinds.
- .NET 8.0 SDK or later
- A MySQL database instance
- NuGet packages:
Dapperv2.1.35MySql.Datav9.1.0xunitv2.9.2
cd DapperUtcConversion
dotnet runYou will need a MySQL connection string configured before running.
If you found this useful and you want to learn more about C#, .NET, and software engineering, subscribe to the free Dev Leader Weekly newsletter:
Subscribe to Dev Leader Weekly
- All Links
- Website - Dev Leader
- YouTube - Dev Leader
- YouTube - Dev Leader Path To Tech
- YouTube - Dev Leader Podcast
- YouTube - CodeCommute
- Newsletter - Dev Leader Weekly
- LinkedIn - Nick Cosentino
- GitHub - ncosentino
- Twitter/X - Dev Leader
- Threads - Dev Leader
- Bluesky - Dev Leader
- Mastodon - Dev Leader
- Facebook - Dev Leader
- TikTok - Dev Leader
- Twitch - Dev Leader
- Stack Overflow - Nick Cosentino
Powered by BrandGhost 👻