如何通过 dapper 将 C# 对象模型作为类型传递给 postgresql 函数

How to pass C# object model as type to postgresql function by dapper

我试图将 C# 对象模型作为 postgresql 类型传递给 dapper 来运行,但我收到此错误:

System.NotSupportedException: The CLR type System.Data.DataTable isn't natively supported by Npgsql or your PostgreSQL. To use it with a PostgreSQL composite you need to specify DataTypeName or to map it, please refer to the documentation.

我的 postgresql 类型是 image 和 url 属性。

这是我在 postgresql 中的函数:

CREATE OR REPLACE FUNCTION public.createapp(applicationid text, images image)
    RETURNS void
    LANGUAGE 'plpgsql'
AS $BODY$
BEGIN
    INSERT INTO app 
                     (
                         id,
                         applicationid,
                         images
                     )
                VALUES
                    (
                         uuid_generate_v4(),
                         applicationid,
                         images
                    );
    
END
$BODY$;

我的图像模型是:

public class Image
{
    public string Url { get; set; }
}

这是我的 C# Dapper 存储库代码:

var parameters = new DynamicParameters();
parameters.Add("applicationid", application.ApplicationId);
parameters.Add("images", application.Images);
var result = await GetDb().QueryFirstOrDefaultAsync("createapp", parameters, commandType: CommandType.StoredProcedure);

如何将此参数传递给我的函数?

您需要像这样在启动时注册您的客户类型:

SqlMapper.AddTypeHandler(new PgTypeHandler<SomeType>());

然后在 sql 脚本参数中定义您的类型,如下所示: @images::sometype

internal class PgTypeHandler<T> : SqlMapper.TypeHandler<T>
    {
        public override T Parse(object value)
        {
            return (T)value;
        }

        public override void SetValue(IDbDataParameter parameter, T value)
        {
            parameter.Value = value;
        }
    }

更多文档: https://www.npgsql.org/doc/

我通过在 startup.cs 中添加 MapComposite 解决了这个问题:

NpgsqlConnection.GlobalTypeMapper.MapComposite<Model.Entities.Image>("image");

"image" 是我的 postgresql 类型。