Skip to content

How to use alternate type "REAL" (JulianDay) for DateTimes in EFcore? #24714

Description

@springy76

Microsoft.Data.Sqlite has support for this: https://docs.microsoft.com/en-us/dotnet/standard/data/sqlite/types#alternative-types : Using REAL (JulianDay) instead of TEXT (ISO8601 formatted string).

But how do I enable this for EFcore for newly written data? (Reading existing databases already seems to work fine)

I tried
builder.Property("name").HasColumnType("REAL")
and
builder.Property("name").HasConversion<double>() or .HasConversion<float>()

I tried both each other exclusive and in combination:

  • HasColumnType only reflects in create table but uses still TEXT for new data (used SQLite's typeof() function to verify)
  • HasConvertion just fails on creating initial SQL

In contrast in order to use binary blob GUIDs (instead of strings) just works by using .HasColumnType("BLOB").HasConversion<byte[]>().

I fear I have to write a converter which calculates the JulianDay in advance?

[EF 5.0.5 on netcore3.1 and net5]

Activity

  1. ajcvickers commented on Apr 23, 2021

    @ajcvickers
    Contributor
  2. bricelam commented on Apr 23, 2021

    @bricelam
    Contributor

    Looks like changing DbParameter.DbType would require a custom type mapping...

    Instead, you can copy the logic into a value converter:

    modelBuilder.Entity<MyEntity>()
        .Property(e => e.MyDateTimeProperty)
        .HasConversion(ToJulianDate, FromJulianDate);

    private static double ToJulianDate(DateTime dateTime)
    {
    // computeJD
    var Y = dateTime.Year;
    var M = dateTime.Month;
    var D = dateTime.Day;
    if (M <= 2)
    {
    Y--;
    M += 12;
    }
    var A = Y / 100;
    var B = 2 - A + (A / 4);
    var X1 = 36525 * (Y + 4716) / 100;
    var X2 = 306001 * (M + 1) / 10000;
    var iJD = (long)((X1 + X2 + D + B - 1524.5) * 86400000);
    iJD += dateTime.Hour * 3600000 + dateTime.Minute * 60000 + (long)((dateTime.Second + dateTime.Millisecond / 1000.0) * 1000);
    return iJD / 86400000.0;
    }

    private static DateTime FromJulianDate(double julianDate)
    {
    // computeYMD
    var iJD = (long)(julianDate * 86400000.0 + 0.5);
    var Z = (int)((iJD + 43200000) / 86400000);
    var A = (int)((Z - 1867216.25) / 36524.25);
    A = Z + 1 + A - (A / 4);
    var B = A + 1524;
    var C = (int)((B - 122.1) / 365.25);
    var D = (36525 * (C & 32767)) / 100;
    var E = (int)((B - D) / 30.6001);
    var X1 = (int)(30.6001 * E);
    var day = B - D - X1;
    var month = E < 14 ? E - 1 : E - 13;
    var year = month > 2 ? C - 4716 : C - 4715;
    // computeHMS
    var s = (int)((iJD + 43200000) % 86400000);
    var fracSecond = s / 1000.0;
    s = (int)fracSecond;
    fracSecond -= s;
    var hour = s / 3600;
    s -= hour * 3600;
    var minute = s / 60;
    fracSecond += s - minute * 60;
    var second = (int)fracSecond;
    var millisecond = (int)Math.Round((fracSecond - second) * 1000.0);
    return new DateTime(year, month, day, hour, minute, second, millisecond);
    }

  3. springy76 commented on Apr 26, 2021

    @springy76
    Author

    Would be handy when those static functions would get public for the future.

  4. bricelam commented on Apr 26, 2021

    @bricelam
    Contributor

    We discussed this as a team, and decided that it would be good if the EF Core SQLite provider handled this automatically.

    Configuraiton SqliteParameter.SqliteType
    .Property(e =>e.Char).HasColumnType("INTEGER") Integer
    .Property(e =>e.DateTime).HasColumnType("REAL") Real
    .Property(e =>e.DateTimeOffset).HasColumnType("REAL") Real
    .Property(e =>e.Guid).HasColumnType("BLOB") Blob
    .Property(e =>e.TimeSpan).HasColumnType("REAL") Real

    📝 Note to implementor: The SQL literal format should also reflect the mapping.

  5. springy76 commented on Apr 27, 2021

    @springy76
    Author

    Please consider providing provider-specific extension methods which don't use strings for the 4-5 native types SQLite interprets.

  6. springy76 commented on Apr 27, 2021

    @springy76
    Author

    Btw: HasConversion (on 5.0.5) only accepts expressions .HasConversion(dt => ToJulianDate(dt), real => FromJulianDate(real)) - or do I miss an additional namespace/assembly for additional extension methods? (there are so many of them).

  7. ajcvickers commented on Apr 27, 2021

    @ajcvickers
    Contributor

    @springy76 This is by design. The expressions are inserted into the larger materialization expression, which is in turn compiled into a delegate for fast materialization.

  8. springy76 commented on Apr 27, 2021

    @springy76
    Author

    Ok... I additionally had to create an explicit converter to use it against nullable DateTime? fields as well:

    var julianDateConverter = new ValueConverter<DateTime, double>(
        dt => ToJulianDate(dt), 
        real => FromJulianDate(real));
    

    (I somewhere did read that converters always ignore null?)

  9. ajcvickers commented on Apr 27, 2021

    @ajcvickers
    Contributor

    (I somewhere did read that converters always ignore null?)

    Yes,

  10. springy76 commented on Apr 27, 2021

    @springy76
    Author

    The values are stored as real "REAL" now 👍 (using .HasColumnType("REAL").HasConversion(julianDateConverter))

    But I'm not quite happy with the queries

    var now = DateTime.UtcNow;
    context.Elements.Where(e => e.Added > now).ToList();
    context.Elements.Where(e => e.Added > DateTime.UtcNow).ToList();
    

    First one uses string parameter (DbType = String) but at least a julian day floating point value:

    info: Microsoft.EntityFrameworkCore.Database.Command[20101]
          Executed DbCommand (0ms) [Parameters=[@__now_0='2459332.189668947' (DbType = String)], CommandType='Text', CommandTimeout='30']
          SELECT "e"."ElementId", "e"."Added", "e"."Kind", "e"."Name", "e"."ParentId", "e"."HashgroupId", "e"."IntegrationCategoryId"
          FROM "Elements" AS "e"
          WHERE "e"."Added" > @__now_0
    

    and for the second one I doubt anything will create a JulianDate before comparing real-value with string-value:
    WHERE "e"."Added" > rtrim(rtrim(strftime('%Y-%m-%d %H:%M:%f', 'now'), '0'), '.')

    The second query was just for testing, won't use that for anything productive.

  11. bricelam commented on Apr 27, 2021

    @bricelam
    Contributor

    The method translators will also need to be updated to understand the conversion.

  12. added this to the Backlog milestone on May 4, 2021
  13. added theissue type on Jun 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions