Search code examples
c#postgresqldapper

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:

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.

My postgresql type is image with url property.

This is my function in 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$;

My image model is:

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

And this is my C# Dapper repository code:

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?


Solution

  • I solved this by add MapComposite in startup.cs:

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

    That "image" is my postgresql type.