在 ASP.NET Core 8 Web API 中,我需要在使用
DateOnly
(8.0.2) 和 Npgsql.EntityFrameworkCore.PostgreSQL
(4.0.1) 加密后将 C# EntityFrameworkCore.DataEncryption
实体属性存储在 PostgreSQL 文本列中。
我正在使用值转换器将
DateOnly
转换为加密前的字符串:
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);
}
然后我将该列映射到实体配置中的“文本”:
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();
}
表格配置为:
CREATE TABLE public.claimant
(
id varchar(36) NOT NULL,
birth_date text NULL,
);
我遇到错误
列“birth_date”的类型为日期,但表达式的类型为文本
数据库日志显示它正在尝试将加密的字符串插入到列中。
然后我尝试删除加密和列映射,仍然得到相同的错误,但现在插入的参数是
@p1='1981-06-28T00:00:00.0000000Z' (DbType = DateTime)
弗兰克是对的,但错误并不在于桌子本身。它位于相应的历史表上,该历史表在插入时由触发器写入,因此我没有立即注意到它。历史表列上的类型仍然是 DATE。