2

I have a couple of classes that need to have one or two properties (out of several dozen) mapped to a column on a table that has a different column name. I don't want to map all of the properties, when only two differ from the column names in the database.

I can't find decent docs on all of the various mapping options that can be used with the CustomPropertyTypeMap, they all just show mapping the entire object with the CustomPropertyTypeMap (as does the Dapper tests class). When I use the following:

// Set up custom repository parameter mappings.
var map = new CustomPropertyTypeMap(typeof(T),
    (type, columnName) => type
        .GetProperties()
        .FirstOrDefault(
            prop => prop.GetCustomAttributes(false)
                .OfType<RepositoryParameterAttribute>()
                .Any(attr => attr.ParameterName == columnName)));

Dapper.SqlMapper.SetTypeMap(typeof(T), map);

// Query the database
items = await databaseConnection.QueryAsync<T>(
    storedProcedure,
    itemParameters,
    commandType: CommandType.StoredProcedure,
    transaction: transaction);

The properties that are not decorated with a RepositoryParameterAttribute return null (or 0). Can I use this to map just specific properties and let Dapper hydrate the remaining, non-decorated attributes, or am I going to have to do something custom?

Thanks.

Johnathon Sullinger
  • 7,097
  • 5
  • 37
  • 102

1 Answers1

0

Dapper.FluentMap allows you to configure mappings from POCO properties to column tables. It does this by using the CustomPropertyTypeMap and using the DefaultTypeMap as fallback.

It's available as NuGet package, but you could also take a look at the source and see how I implemented the CustomerPropertyTypeMap and create a more simple implementation for yourself.

Henk Mollema
  • 44,194
  • 12
  • 93
  • 104
  • 1
    Thanks I'll take a look at it. At the moment I'm using [this solution](http://stackoverflow.com/questions/8902674/manually-map-column-names-with-class-properties) but requires a bit of reflection up front on my end. My queries are in a generic method so I don't know ahead of time in the service layer what needs mapping without reflection. I'll look at Dapper.FluentMap and see if it resolves this! – Johnathon Sullinger Oct 29 '14 at 15:13
  • Dapper.FluentMap actually uses the fallback mapper solution proposed there, it's just a more complete solution with mapping classes and without reflection hassle. – Henk Mollema Oct 29 '14 at 15:18
  • Nice, appreciate the help. I'll get it pulled down! – Johnathon Sullinger Oct 29 '14 at 15:18