Reputation: 774
I'm trying to use Dapper with Postgres and for the life of me I can't get the column mapping to work. I'm using camel_casing for columns in the database.
This is the table I'm working with:
create table test_table
(
id uuid default gen_random_uuid() not null
constraint test_table_pk
primary key,
first_name varchar(256) not null,
created_date timestamp not null
);
alter table test_table owner to root;
I have made the following application to recreate the issue
namespace DapperIssue {
class Program {
static void Main(string[] args) {
NpgsqlConnection.GlobalTypeMapper.UseNodaTime();
DefaultTypeMap.MatchNamesWithUnderscores = true;
using (var conn =
new NpgsqlConnection("CONNECTIONSTRING FOR DATABASE")) {
conn.Open();
var result = conn.Query<T1>(@"
SELECT id, first_name FROM test_table", new { });
var result2 = conn.Query<T2>(@"
SELECT id, first_name, created_date FROM test_table", new { });
}
}
}
//public record T1(Guid Id, string FirstName) { }
public class T1 {
public Guid Id { get; }
public string FirstName { get; }
public T1(Guid id, string firstName) {
Id = id;
FirstName = firstName;
}
}
public record T2(Guid Id, string FirstName, Instant CreateDate) {
}
}
The application is failing when trying to query the database with the following error:
System.InvalidOperationException: A parameterless default constructor or one matching signature (System.Guid id, System.String first_name)
My understanding was that setting DefaultTypeMap.MatchNamesWithUnderscores = true should make this work.
Using Dapper "2.0.78" and NpgSql "5.0.3"
Upvotes: 2
Views: 3206
Reputation: 35544
This seems to be an open issue in dapper. Read more DefaultTypeMap.MatchNamesWithUnderscores is ignored for ctor parameters and Added support for MatchNamesWithUnderscores and ctor parameters.
Adding a parameterless constructor should fix your problem. The columns should be mapped to the properties of the class with the named setting.
Upvotes: 1