c# - 映射 IDataReader 时未调用 AutoMapper TypeConverter

标签 c# .net automapper idatareader

我有几个模型想使用 AutoMapper 进行映射。 Automapper 设置为从 IDataReader 映射到模型类。问题是我需要在我的映射器上设置一个 ITypeConverter,这样我就可以为每个模型枚举有限的次数。 我不想为每个模型创建许多继承自 ITypeConverter 的类。

示例模型:

public class Customer: IModel
{
    public FirstName { get; set; }
    public LastName { get; set; }
}

映射器类:

public static class AutoMappingConfig
{
    public static void Configure()
    {
        // I would have many other mappings like the one below. All taking an IDataReader and mapping to a model inheriting from IModel
        Mapper.CreateMap<IDataReader, Customer>()
            .ForMember(x => x.FirstName, o => o.MapFrom(s => s.GetString(s.GetOrdinal("first_name")))
            .ForMember(x => x.LastName, o => o.MapFrom(s => s.GetString(s.GetOrdinal("last_name"))));

        // I would have many of the following. All taking an IDataReader and mapping to an IEnumerable model object
        Mapper.CreateMap<IDataReader, IEnumerable<Customer>>().ConvertUsing<ModelConverter<Customer>>();
    }
}

转换器:

public class ModelConverter<T>: ITypeConverter<IDataReader, IEnumerable<T>> where T: IModel
{
    public IEnumerable<T> Convert(ResolutionContext context)
    {
        var dataReader = (IDataReader) context.SourceValue;
        var rowCount = 0;
        var collection = new List<T>();

        // The purpose for this ModelConverter is the a maximum row count of 10
        while (dataReader.Read() && rowCount < 10)
        {
            var item = Mapper.Map<IDataReader, T>(dataReader);
            collection.Add(item);
            rowCount++;
        }

        return collection;
    }
}

注意:问题不在于 ModelConverter 类,因为当我传入 IDataReader 时它从未被调用。我已经尝试使用另一个类的类似映射系统,它被调用并成功处理了映射。

当我运行以下代码时,返回的值是具有空映射的项目列表。根本不会调用 ModelConverter 类。上面的代码适用于 IDataReader 以外的任何输入。 AutoMapper 正在对 IDataReader 做一些特别的事情,但我不确定此时如何继续 ITypeConverter。

var customers = Mapper.Map<IDataReader, IEnumerable<Customer>>(dataReader);

在上面的代码中,dataReader 是 IDataReader 对象。

最佳答案

抱歉,数据读取器当前不支持类型转换器。

关于c# - 映射 IDataReader 时未调用 AutoMapper TypeConverter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25004543/

相关文章:

c# - AutoMapper 3.1.1 和 Entity Framework 6.1 代理对象

c# - AutoMapper 和 EF 实体 - 忽略所有关系

c# - 如何在 AutoMapper 中全局使用忽略?

c# - DataView.Sort - 不仅仅是 asc/desc(需要自定义排序)

c# - EntityFramework 4.0 POCO代理问题

c# - visual studio 2015 在构建时卡住,杀死 find.exe(三次)完成构建过程

.net - 在 Win Forms NotifyIcon 上禁用 Alt-F4

c# - 将字符串转换为 Unicode 字符

c# - 非单调增加 dts 到流中的复用器

c# - 具有多个参数的自定义验证属性