2

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

我找不到关于可与 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 水合剩余的未修饰属性,还是我必须做一些自定义的事情?

谢谢。

4

1 回答 1

0

Dapper.FluentMap允许您配置从 POCO 属性到列表的映射。它通过使用CustomPropertyTypeMap和使用DefaultTypeMap作为后备来做到这一点。

它以NuGet 包的形式提供,但您也可以查看源代码并了解我是如何实现的,CustomerPropertyTypeMap并为自己创建一个更简单的实现。

于 2014-10-29T15:11:33.550 回答