Skip to content

AutoClassMapper

Chris Marisic edited this page Mar 21, 2016 · 11 revisions

Out of the box, Dapper Extensions has a default ClassMapper (AutoClassMapper) that handles the population of POCOs. The ClassMapper facility is important because it is what allows us to keep the POCOs attribute free. You can easily change the behavior of Dapper Extensions, by supplying your own implementation of ClassMapper.

DapperExtensions.DapperExtensions.DefaultMapper = typeof(MyCustomClassMapper<>);

AutoClassMapper Assumptions

The default AutoClassMapper makes certain assumptions about your database schema and POCOs.

  • AutoClassMapper assumes that your table names are singular (Ex: Car table name and Car POCO name).
  • Each POCO has at least one property named Id or ends with Id.
  • If multiple properties end with Id, Dapper Extensions will use the first Id property as the primary key.
  • If the Id property is determined to be an Integer, the KeyType will be set to Identity.
  • If the Id property is determined to be a Guid, the KeyType will be set to Guid.
  • If the id property is anything other than an Integer our Guid, the KeyType will be set to Assigned.

You can override these conventions in a per entity scenario with a customized mapping.

PluralizedAutoClassMapper

The AutoClassMapper assumes that your database table names are singular (Ex: Car table instead of Cars). Since it is such a common request, we have included a ClassMapper (PluralizedAutoClassMapper) that will attempt to pluralize any references to table names. To configure Dapper Extensions with the PluralizedAutoClassMapper, simply include the following code at startup:

DapperExtensions.DapperExtensions.DefaultMapper = typeof(PluralizedAutoClassMapper<>);

Customized PluralizedAutoClassMapper

Since the English language has so many rules for pluralization, the PluralizedAutoClassMapper will not provide you with the correct pluralization for every possible scenario. Also, there may be some situations where your database table names do not follow the same pluralization rules as Dapper Extensions. In these situations, you can easily override the defaults and inject your own rules.

In the example below, a CustomPluralizedMapper is created that maps Person to a Persons table. Without the override, the PluralizedAutoClassMapper would map Person to a People table:

public class CustomPluralizedMapper<T> : PluralizedAutoClassMapper<T> where T : class 
{
    public override void Table(string tableName)
    {
        if(tableName.Equals("Person", StringComparison.CurrentCultureIgnoreCase))
        {
            TableName = "Persons";
        }

        base.Table(tableName);
    }
}
DapperExtensions.DapperExtensions.DefaultMapper = typeof(CustomPluralizedMapper<>);
You can’t perform that action at this time.