使用CustomPropertyTypeMap映射特定属性

时间:2014-10-29 02:58:42

标签: c# sql data-access-layer dapper dapper-extensions

我有几个类需要将一个或两个属性(几十个)映射到具有不同列名的表上的列。当只有两个属性与数据库中的列名不同时,我不想映射所有属性。

我无法在可以与CustomPropertyTypeMap一起使用的所有各种映射选项上找到合适的文档,它们都只显示使用CustomPropertyTypeMap映射整个对象(就像Dapper测试类一样)。当我使用以下内容时:

// 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);

未使用RepositoryParameterAttribute修饰的属性返回null(或0)。我是否可以使用它来映射特定的属性,让Dapper保留剩余的,未装饰的属性,或者我将不得不做一些自定义的事情?

感谢。

1 个答案:

答案 0 :(得分:0)

Dapper.FluentMap允许您配置从POCO属性到列表的映射。它通过使用CustomPropertyTypeMap并使用DefaultTypeMap作为后备来完成此操作。

它以NuGet package的形式提供,但您也可以查看source,看看我是如何实现CustomerPropertyTypeMap并为自己创建更简单的实现。