Using CustomPropertyTypeMap to map specific properties

雨燕双飞 提交于 2020-01-15 05:49:07

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/26622063/using-custompropertytypemap-to-map-specific-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!