尝试使用 PgPartner 等库来轻松完成批量添加。查看 PgPartner:https://www.nuget.org/packages/PgPartner/
https://github.com/SourceKor/PgPartner#bulkadd-npgsqlconnection-extension
用法:
// Domain Model Objects
var samples = new List<Sample>()
{
new Sample { Id = Guid.NewGuid(), Name = "Test", ItemSum = 200, ItemAmount = 10 },
new Sample { Id = Guid.NewGuid(), Name = "Test 2", ItemSum = 400, ItemAmount = 20 },
new Sample { Id = Guid.NewGuid(), Name = "Test 3", ItemSum = 800, ItemAmount = 30 },
new Sample { Id = Guid.NewGuid(), Name = "Test 4", ItemSum = 1200, ItemAmount = 40 },
new Sample { Id = Guid.NewGuid(), Name = "Test 5", ItemSum = 2400, ItemAmount = 50 }
};
// Instantiate and open PostgreSQL database connection
using var conn = new NpgsqlConnection("<connection string>");
conn.Open();
// Execute BulkAdd by passing objects to insert into table, single object mapping, database schema, and database table
conn.BulkAdd(
samples,
(mapper, sample) => {
mapper.Map("id", sample.Id, NpgsqlDbType.Uuid);
mapper.Map("name", sample.Name, NpgsqlDbType.Text);
mapper.Map("amount", sample.ItemAmount, NpgsqlDbType.Numeric);
mapper.Map("sum", sample.ItemSum, NpgsqlDbType.Integer);
},
"public",
"\"Samples\""
);