Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EntityFramework Core format DateTime in sqlite database

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?

like image 307
BlackMatrix Avatar asked Mar 13 '18 16:03

BlackMatrix


People also ask

Does EF core work with SQLite?

This database provider allows Entity Framework Core to be used with SQLite. The provider is maintained as part of the Entity Framework Core project.

Does SQLite have datetime?

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.

What is the use of date () function in SQLite?

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.

How can create SQLite database in Entity Framework Core?

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.


2 Answers

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();
}
like image 64
bricelam Avatar answered Nov 01 '22 22:11

bricelam


To add on bricelam reply. A better (Shorter and faster) code for trimming miliseconds would be:

property.CurrentValue = value.AddTicks(-value.Ticks % TimeSpan.TicksPerSecond)
like image 33
Desmond Avatar answered Nov 02 '22 00:11

Desmond