Search code examples
npgsqlnodatimelinq2db

NodaTime with Linq2Db


How can I configure T4 POCO generation in Linq2Db to generate models that use NodaTime types instead of System.DateTime?

I'm using PostgreSQL with Npgsql.


Solution

  • To substitute standard DateTime classes you have to modify your T4 template in the following way:

    // loading database schema
    LoadPostgreSQLMetadata(...)
    
    // modifying default mapping
    foreach (var t in Tables.Values)
    {
        foreach (var c in t.Columns.Values)
        {
            switch (c.Type)
            {
                case "DateTime"       : c.Type = "NodaTime.LocalDateTime";   break;
                case "DateTime?"      : c.Type = "NodaTime.LocalDateTime?";  break;
                case "DateTimeOffset" : c.Type = "NodaTime.OffsetDateTime";  break;
                case "DateTimeOffset?": c.Type = "NodaTime.OffsetDateTime?"; break;
            }
        }
    }
    
    // generating model
    GenerateModel();