Bug #105091 DateTimeOffset is Inappropriately Shifted on Deserialization from Database
Submitted: 30 Sep 2021 19:13 Modified: 8 Jun 2022 19:07
Reporter: Daniel King Email Updates:
Status: Closed Impact on me:
None 
Category:Connector / NET Severity:S3 (Non-critical)
Version:8.0.25 OS:Any
Assigned to: CPU Architecture:x86

[30 Sep 2021 19:13] Daniel King
Description:
Tested with .NET app running on Win10 (local) and Linux (via Docker) + MySQL running on Linux (via Docker)

## Version Info

- MySQL version: `8.0.25`
- .NET runtime version: `Core 3.1`
- EF Core version: `5.0.5`
- MySQL.EntityFrameworkCore version: `5.0.5`

## Description

When using a `DateTimeOffset` column on an entity, MySQL is returning data shifted from the original timestamp (eg 12:00 -0400) to the UTC timestamp without updating the timezone info (eg returning 16:00 -0400 when it should be either 16:00 +0000 or the originally provided 12:00 -0400). Note, this applies regardless if the original `DateTimeOffset` is in UTC or local time.

Further, changing the timezone of the database (either globally or for the session) does not seem to affect this behavior.

Note, the correct value is stored in the database, so this appears to be a deserialization issue.

How to repeat:
## Code to Reproduce

I have created a public GitHub repo with a C# project to reproduce this issue [here](https://github.com/danielloganking/mysql-efcore-bugs). This topic refers to [bug 1](https://github.com/danielloganking/mysql-efcore-bugs#1-datetimeoffset-inappropriate-time-s...) as listed in that repo.

A pseudo-test case which reproduces the bug is included below for convenience:

```csharp
var now = DateTimeOffset.Now;
var entity = new Entity() { Id = Guid.NewGuid() }; // DateTimeOffset is not explicitly set but is autocomputed on insert
dbContext.Entities.Add(entity);
dbContext.SaveChanges();

entity.DateTimeOffset.Should().BeCloseTo(now, 30_000); // fails due to invalid shift
```

Suggested fix:
DateTimeOffset should deserialize using the UTC timezone rather than the Local timezone.

Note, this is possible to do manually using `.HasConversion(v => v, v => new DateTimeOffset(DateTime.SpecifyKind(v.DateTime, DateTimeKind.Utc)))` in the `DbContext.OnModelCreating` but this work around breaks ef generated migrations. If using said work around the migration will not include `.Annotation("MySQL:ValueGenerationStrategy", MySQLValueGenerationStrategy.IdentityColumn)`; it must then be added manually to or the database will not properly set the value of the column on insert/update.
[6 Feb 2022 11:27] MySQL Verification Team
Hello Daniel,

Thank you for the report and test case.

regards,
Ashwini
[8 Jun 2022 19:07] Daniel Valdez
Posted by developer:
 
This bug has been fixed in consequence of another work done for EFCore 6.0. Please use the latest version of EF Core.
It will be included in the next release, v8.0.30.