简体   繁体   English

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

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

I'm trying to pass C# object model as postgresql type to function by dapper but I get this error: I'm trying to pass C# object model as postgresql type to function by dapper but I get this error:

System.NotSupportedException: The CLR type System.Data.DataTable isn't natively supported by Npgsql or your PostgreSQL. System.NotSupportedException: Npgsql 或您的 PostgreSQL 本身不支持 CLR 类型 System.Data.DataTable。 To use it with a PostgreSQL composite you need to specify DataTypeName or to map it, please refer to the documentation.要将它与 PostgreSQL 组合一起使用,您需要指定 DataTypeName 或 map 它,请参阅文档。

My postgresql type is image with url property.我的 postgresql 类型是具有 url 属性的image

This is my function in postgresql:这是我在 postgresql 中的 function:

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$;

My image model is:我的形象 model 是:

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

And this is my C# Dapper repository code:这是我的 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);

How can I pass this parameter to my function?如何将此参数传递给我的 function?

you need to register your custome type in startup like this:您需要像这样在启动时注册您的客户类型:

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

and then define your type in sql script parameter like this: @images::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;
        }
    }

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

I solved this by add MapComposite in startup.cs:我通过在 startup.cs 中添加 MapComposite 解决了这个问题:

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

That "image" is my postgresql type."image"是我的 postgresql 类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM