Skip to content

Latest commit

 

History

History

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 

README.md

DapperUtcConversion - Handling UTC DateTime Conversion with Dapper in C#

YouTube Blog Newsletter All Links LinkedIn

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.

Getting Started

Prerequisites

  • .NET 8.0 SDK or later
  • A MySQL database instance
  • NuGet packages:
    • Dapper v2.1.35
    • MySql.Data v9.1.0
    • xunit v2.9.2

Running the Project

cd DapperUtcConversion
dotnet run

You will need a MySQL connection string configured before running.

Newsletter

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

Connect with Dev Leader


BrandGhost

Powered by BrandGhost 👻