How to map column names to class properties in Dapper?

dapper

Question

The Dapper micro ORM is new to me. I can use it so far for basic ORM-related tasks, but I am unable to link database column names to class attributes.

I have the following database table, as an illustration:

Table Name: Person
person_id  int
first_name varchar(50)
last_name  varchar(50)

I also teach a lesson called "Person,"

public class Person 
{
    public int PersonId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Please take notice that the names of my columns in the database vary from the names of the properties of the class to which I am attempting to transfer the information I received from the query result.

var sql = @"select top 1 PersonId,FirstName,LastName from Person";
using (var conn = ConnectionFactory.GetConnection())
{
    var person = conn.Query<Person>(sql).ToList();
    return person;
}

The column names in the preceding code don't correspond to the attributes of the object (Person), hence it won't run. Is there anything I can do in Dapper to manually map (for example) this situationperson_id => PersonId ) the names of the object properties' columns?

2
167
5/13/2019 3:51:44 PM

Accepted Answer

This is effective:

var sql = @"select top 1 person_id PersonId, first_name FirstName, last_name LastName from Person";
using (var conn = ConnectionFactory.GetConnection())
{
    var person = conn.Query<Person>(sql).ToList();
    return person;
}

Dapper does not have a mechanism for specifying a Section Attribute, but I am not opposed to adding support for it as long as we do not import the dependency.

73
4/19/2017 1:51:57 PM

Expert Answer

The following should work for a while:

Dapper.DefaultTypeMap.MatchNamesWithUnderscores = true;
75
12/30/2015 8:35:02 PM


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow