Manually Map column names with class properties

dapper

Question

I am new to Dapper Micro ORM. So far i am able to use it for simple ORM related stuffs but i am not able to map the database column names with the class properties. For example:

I have the database table as follows:

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

and i have the class called Person

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

Please note that my column names in the table are different from the property name of the class to which i am trying to map the data which i got 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 above code won't work as column names won't match with object's (Person) properties. In this scenario, is there anything i can do in Dapper to manually map (e.g person_id => PersonId) the column names with object properties?

Any clue or help would be highly appreciated.

Accepted Answer

This works fine:

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 has no facility that allows you to specify a Column Attribute, I am not against adding support for it, providing we do not pull in the dependency.


Expert Answer

For some time, the following should work:

Dapper.DefaultTypeMap.MatchNamesWithUnderscores = true;



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why