You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Npgsql和Dapper操作PostgreSQL复合类型时参数不支持异常的解决求助

使用Npgsql和Dapper操作PostgreSQL复合类型时参数不支持异常的解决求助

我现在在使用Npgsql和Dapper操作PostgreSQL数据库,其中有一个自定义的复合数据类型:

create type datetimeoffset as
(
    "DateTimeUtc" timestamp without time zone,
    "Offset" smallint
);

为了在C#里对应这个复合类型,我定义了如下实体类:

public class PgDateTimeOffset
 {
     public PgDateTimeOffset(DateTime dateTimeUtc, short offset)
     {
         DateTimeUtc = DateTime.SpecifyKind(dateTimeUtc, DateTimeKind.Utc);
         Offset = offset;
     }

     public DateTime DateTimeUtc { get; set; }
     public short Offset { get; set; }
}

同时我创建了一张使用该复合类型的表:

create table mytable
(
    Id int not null generated always as identity,
    Timestamp datetimeoffset
);

接着写了插入数据的方法:

public void Insert(PgDateTimeOffset timestamp)
{
    Connection.Execute("INSERT INTO mytable (Timestamp) VALUES (@timestamp)", new { timestamp });
}

另外我还实现了一个Dapper的类型处理器,用来处理DateTimeOffset和自定义复合类型的转换:

public class DapperDateTimeOffsetTypeHandler: SqlMapper.TypeHandler<DateTimeOffset>
{
    public override void SetValue(IDbDataParameter parameter, DateTimeOffset value)
    {
        // 发送数据时,转换为PgDateTimeOffset实例
        parameter.Value = (PgDateTimeOffset)value;
    }

    public override DateTimeOffset Parse(object value)
    {
        // 读取数据时,将对象转换为DateTimeOffset
        if (value is PgDateTimeOffset composite)
        {
            return composite;
        }
        if(value is DateTimeOffset dto)
        {
            return dto;
        }
        if (value is DateTime dt)
        {
            return dt;
        }
        throw new DataException("Unexpected type when converting to DateTimeOffset.");
    }
}

并且已经注册了这个类型处理器:

SqlMapper.AddTypeHandler(new DapperDateTimeOffsetTypeHandler());

复合类型的映射也已经通过Npgsql注册完成:

var dataSourceBuilder = new NpgsqlDataSourceBuilder(connectionString);
dataSourceBuilder.MapComposite<PgDateTimeOffset>("datetimeoffset");
var dataSource = dataSourceBuilder.Build();

但现在我一直遇到这个异常:

System.NotSupportedException
  HResult=0x80131515
  Message=The member timestamp of type Neurologistica.Data.Repositories.PostgreSql.PgDateTimeOffset cannot be used as a parameter value
  Source=Dapper
  StackTrace:

有没有大佬能帮我看看问题出在哪?我是不是漏掉了什么关键步骤?

备注:内容来源于stack exchange,提问作者Yván Ecarri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 10:02:57