Last active
August 26, 2022 08:41
-
-
Save GeorgDangl/b90370124720ed8fed9539509aafd155 to your computer and use it in GitHub Desktop.
Handling DateTimeOffset in Entity Framework Core 3.0 with SQLite, see https://blog.dangl.me/archive/handling-datetimeoffset-in-sqlite-with-entity-framework-core-in-test-scenarios/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
protected override void OnModelCreating(ModelBuilder builder) | |
{ | |
base.OnModelCreating(builder); | |
if (Database.ProviderName == "Microsoft.EntityFrameworkCore.Sqlite") | |
{ | |
// SQLite does not have proper support for DateTimeOffset via Entity Framework Core, see the limitations | |
// here: https://docs.microsoft.com/en-us/ef/core/providers/sqlite/limitations#query-limitations | |
// To work around this, when the Sqlite database provider is used, all model properties of type DateTimeOffset | |
// use the DateTimeOffsetToBinaryConverter | |
// Based on: https://github.com/aspnet/EntityFrameworkCore/issues/10784#issuecomment-415769754 | |
// This only supports millisecond precision, but should be sufficient for most use cases. | |
foreach (var entityType in builder.Model.GetEntityTypes()) | |
{ | |
var properties = entityType.ClrType.GetProperties().Where(p => p.PropertyType == typeof(DateTimeOffset) | |
|| p.PropertyType == typeof(DateTimeOffset?)); | |
foreach (var property in properties) | |
{ | |
builder | |
.Entity(entityType.Name) | |
.Property(property.Name) | |
.HasConversion(new DateTimeOffsetToBinaryConverter()); | |
} | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SQLite only stores up to .001 second precision due to the | |
// internal conversion to long / unix timestamp | |
var ticksToSubtract = myDate.Ticks % 1000; | |
myDate = myDate.Subtract(TimeSpan.FromTicks(ticksToSubtract)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment