I'm using EF Core 2.0 with SQLite and I want to reduce the size of my database without loosing the human readable datetime value in my table column. Currently the data context stores the full DateTime CLR object as a a string like "2018-03-10 16:18:17.1013863" but in my case "2018-03-10 16:18:17" would be enought. What I have to do?
This database provider allows Entity Framework Core to be used with SQLite. The provider is maintained as part of the Entity Framework Core project.
Date and Time Datatype. SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values: TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.
The SQLite date() function is used to calculate the date and return it in the format 'YYYY-MM-DD'. The SQLite datetime() function is used to calculate a date/time value, and return it in the format 'YYYY-MM-DD HH:MM:SS'. The SQLite julianday() function returns the date according to julian day.
Create SQLite Database from code with EF Core MigrationsGenerate new EF Core migration files by running the command dotnet ef migrations add InitialCreate from the project root folder (where the WebApi. csproj file is located), these migrations will create the database and tables for the . NET Core API.
The fractional seconds aren't stored if they're zero. You can safely remove them from the existing data. Update your application to not specify them. You can do this eagerly (when you set DateTime
values on your entities) or lazily during SaveChanges
.
public override int SaveChanges()
{
var dateTimeProperties =
from e in ChangeTracker.Entries()
where e.State == EntityState.Added
|| e.State == EntityState.Modified
from p in e.Properties
where p.CurrentValue is DateTime
select p;
foreach (var property in dateTimeProperties)
{
// Strip millisecond
var value = (DateTime)property.CurrentValue;
property.CurrentValue = new DateTime(
value.Year,
value.Month,
value.Day,
value.Hour,
value.Minute,
value.Second);
}
return base.SaveChanges();
}
To add on bricelam reply. A better (Shorter and faster) code for trimming miliseconds would be:
property.CurrentValue = value.AddTicks(-value.Ticks % TimeSpan.TicksPerSecond)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With