DEV Community

Discussion on: How to map column names to class properties with Dapper

Collapse
 
buinauskas profile image
Evaldas Buinauskas • Edited

I do prefer to do it slightly different by keeping classes clean. This code could still break if someone changes alias and keeps description attribute untouched.

You can assign correct aliases by using nameof(Class.PropertyName) within your query string. This guarantees that column names are mapped correctly and makes refactoring so much easier in case you want to change a property name.

var sql = $@"
    SELECT Contact_Cli_ID AS {nameof(Contact.Contact_ID)},
        Clt_ID AS {nameof(Contact.Client_ID)},
        Contact_Cli_Nom AS {namoef(Contact.Nom)},
        Contact_Cli_Prenom AS {nameof(Contact.Prenom)},
        Contact_Tel_Fixe AS {nameof(Contact.Telephone)},
        Contact_Cli_Fax AS {nameof(Contact.Telecopie)},
        Contact_Cli_Mail AS {nameof(Contact.Mail)},
        Contact_Portable AS {nameof(Contact.Portable)}
    FROM Contact_Clients
    ...";

Then your class can stay as is.
๐Ÿ™‚

public class Contact
{
  public int Contact_ID { get; set; }
  public int Client_ID { get; set; }
  public string Nom { get; set; }
  public string Prenom { get; set; }
  public string Telephone { get; set; }
  public string Telecopie { get; set; }
  public string Mail { get; set; }
  public string Portable { get; set; }
}
Collapse
 
michelc profile image
Michel • Edited

Yes. I also don't think it's really worth it, especially since I only use Dapper for small conversion application. But it was fun to try new things.

By the way, I love the nameof(Class.PropertyName) thing. Thanks.

Collapse
 
buinauskas profile image
Evaldas Buinauskas

Might be an overkill, yep.

A few days ago I had to do quite a big refactoring and queries were constructed exactly like this, refactoring was a breeze ๐Ÿ™‚

Cheers!