EF6 Oracle TimeStamp & Date

后端 未结 1 1604
不思量自难忘°
不思量自难忘° 2021-01-29 04:32

I\'m starting to use EntityFramework 6 with Oracle (client 12.x). I have severals tables with DATE columns and TIMESTAMP columns.

All queries generated by EF6 convert .N

相关标签:
1条回答
  • 2021-01-29 04:49

    I've had a similar issue with DATE Oracle type and EF6.1. My workaround was to use the CodeFirstFunctions library (available only for EF6.1 and later) and specify a conversion function first in Oracle:

    create or replace FUNCTION TO_DATE_LOCAL 
    (
      DATETIMETOCONVERT IN VARCHAR2 
    , CONVERTFORMAT IN VARCHAR2 
    ) RETURN DATE AS 
    BEGIN
      RETURN to_date(DATETIMETOCONVERT, CONVERTFORMAT);
    END TO_DATE_LOCAL;
    

    And later in my DbContext:

    [DbFunction("CodeFirstDatabaseSchema", "TO_DATE_LOCAL")]
    public static DateTime ToDateLocal(string dateTimeToConvert, string convertFormat)
    {
        // no need to provide an implementation
        throw new NotSupportedException();
    }
    

    So I can force Entity Framework to use DATE type in a where condition:

    var measurement = 
      context.Measurements
        .Where(m => m.MeasuredAt == 
              PlantContext.ToDateLocal("2016.01.01 10:00:00", "YYYY.MM.DD Hh24:MI:SS"))
        .FirstOrDefault();
    

    Be careful to use capital letters for the function name and for the schema name with CodeFirstFunctions if you use Oracle.

    If you need more details I've written a blog post about this with an example project.

    0 讨论(0)
提交回复
热议问题