我想通过传递复合类型参数来调用 Postgres 数据库中的存储过程,我想使用 Dapper 和 npgsql 最新稳定版本 7.0.
我能够使用 npgsql 版本 6.0.0 和这段代码来实现这个:
// Register the composite type mapper
NpgsqlConnection.GlobalTypeMapper.MapComposite<CustomerType>("customer_type");
var connectionString = "User ID=postgres;Password=test;Host=localhost;Port=5432;Database=testDB;Pooling=true;";
using var con = new NpgsqlConnection(connectionString);
con.Open();
// Call the insert_customer_list stored procedure
var customers = new[]
{
new CustomerType {Name = "John Doe", Email = "[email protected]", Phone = "555-1234"},
new CustomerType {Name = "Jane Smith", Email = "[email protected]", Phone = "555-5678"}
};
var parameters = new DynamicParameters();
parameters.Add("cust_list", customers);
con.Execute("CALL insert_customer_list(@cust_list)", parameters);
Console.WriteLine("Stored procedure executed successfully.");
即使我能够使此代码与升级版本的 npgsql (v7.0.0) 一起使用,
GlobalTypeMapper.MapComposite
方法在此版本中已过时。
文档提到
NpgsqlDataSource 是在 Npgsql 7.0 中引入的,是管理类型映射的推荐方式
但是我找不到合适的文档来制作
NpgsqlDataSource
与 Dapper 一起使用。
使用 npgsql 版本 6.0.0 的一个缺点是我需要调用一个过程并提供其参数,如上面的代码所示 (CALL insert_customer_list(@cust_list)),使用 npgsql 版本 7 可以避免这种情况吗?
我曾尝试通过以下代码更改使它适用于版本 7,但它抛出错误 System.NotSupportedException: 'Npgsql 或您的 PostgreSQL 本身不支持 CLR 类型 DapperNpgsqlExample.CustomerType。要将它与 PostgreSQL 组合一起使用,您需要指定 DataTypeName 或映射它,请参阅文档。'
代码修改
// Register the composite type mapper
////NpgsqlConnection.GlobalTypeMapper.MapComposite<CustomerType>("customer_type");
var connectionString = "User ID=postgres;Password=test;Host=localhost;Port=5432;Database=testDB;Pooling=true;";
var dataSourceBuilder = new NpgsqlDataSourceBuilder(connectionString);
dataSourceBuilder.MapComposite<CustomerType>("customer_type");
using var dataSource = dataSourceBuilder.Build();
using var con = new NpgsqlConnection(connectionString);
con.Open();
// Call the insert_customer_list stored procedure
var customers = new[]
{
new CustomerType {Name = "John Doe", Email = "[email protected]", Phone = "555-1234"},
new CustomerType {Name = "Jane Smith", Email = "[email protected]", Phone = "555-5678"}
};
var parameters = new DynamicParameters();
parameters.Add("cust_list", customers);
con.Execute("insert_customer_list", parameters, commandType: CommandType.StoredProcedure);
Console.WriteLine("Stored procedure executed successfully.");