Using CustomPropertyTypeMap to map specific properties

c# dapper dapper-extensions data-access-layer sql

Question

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.

Popular Answer

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.



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