How to map encrypted DateOnly to text in PostgreS

31 views Asked by At

In an ASP.NET Core 8 Web API, I need to store a C# DateOnly entity property in a PostgreSQL text column after encrypting using Npgsql.EntityFrameworkCore.PostgreSQL (8.0.2) and EntityFrameworkCore.DataEncryption (4.0.1).

I am using a value converter to convert the DateOnly to string before encryption:

public class DateToStringValueConverter : ToStringValueConverter<DateOnly?>
{
    public DateToStringValueConverter()
        : base(dateOnly => Format(dateOnly), stringValue => Parse(stringValue))
    { }

    private static DateOnly? Parse(string? stringValue) =>
        null == stringValue ? null : DateOnly.Parse(stringValue, CultureInfo.InvariantCulture, DateTimeStyles.AllowTrailingWhite);

    private static string? Format(DateOnly? dateOnly) =>
        dateOnly?.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
}

Then I am mapping the column to "text" in the entity configuration:

public void Configure(EntityTypeBuilder<Claimant> builder)
{
    builder.ToTable("claimant").HasKey(k => k.Id);
    builder.Property(p => p.Id).HasColumnName("id");
    builder.Property(p => p.BirthDate).HasColumnName("birth_date").HasColumnType("text").IsEncrypted();
}

And the table is configured as:

CREATE TABLE public.claimant 
(
    id varchar(36) NOT NULL,
    birth_date text NULL,
);

I'm getting an error

Column 'birth_date' is of type date but expression is of type text

The database log shows that it is trying to insert the encrypted string in the column.

Then I tried removing the encryption and column mapping, and I still get the same error, but now the parameter being inserted is

@p1='1981-06-28T00:00:00.0000000Z' (DbType = DateTime)

BirthDate object

1

There are 1 answers

0
dwdjo On

Frank was right, but the error was not on the table itself. It was on a corresponding history table that was being written by a trigger upon the insert, so I didn't notice it right away. The type on the history table column was still DATE.