【问题标题】:AutoMapper Open Generics Mapping Not WorkingAutoMapper 打开泛型映射不起作用
【发布时间】:2017-07-23 18:59:27
【问题描述】:

我正在尝试设置地图以利用开放泛型,但它在运行时无法正常工作。我在 .NET Core 中使用 AutoMapper 5.2。

我有这些模型:

public interface IRestData<T>
{
    T Data { get; }
    IPaging Paging { get; }

    void SetData(T data);
    void SetPaging(IPaging paging);
}

public interface IPaging
{
    int Count { get; }

    void SetCount(int count);
}

public class RestData<T> : IRestData<T>
{
    T _data;
    IPaging _paging = new Paging(0);

    public RestData() {}

    public RestData(T data)
    {
        _data = data;

        if (!typeof(IEnumerable).GetTypeInfo()
                                .IsAssignableFrom(typeof(T)))
            _paging = new Paging(data != null
                                     ? 1
                                     : 0);
    }

    public RestData(T data, IPaging paging)
    {
        _data = data;
        _paging = paging;
    }

    public T Data => _data;
    public IPaging Paging => _paging;

    public void SetData(T data) => _data = data;
    public void SetPaging(IPaging paging) => _paging = paging;
}

public class Paging : IPaging
{
    int _count;

    public Paging() {}

    public Paging(int count)
    {
        _count = count;
    }

    public int Count => _count;
    public void SetCount(int count) => _count = count;
}

我希望能够从一个 RestData 映射到另一个 RestData ,其中 T 不一定相同。我创建了一个看起来像这样的 AutoMapper.Profile(使用界面):

public class CommonProfile : Profile
{
    public CommonProfile()
    {
        CreateMap(typeof(IRestData<>), typeof(IRestData<>))
            .ConvertUsing(typeof(RestDataConverter<,>));
    }
}

我也试过这样(使用具体类型):

public class CommonProfile : Profile
{
    public CommonProfile()
    {
        CreateMap(typeof(RestData<>), typeof(RestData<>))
            .ConvertUsing(typeof(RestDataConverter<,>));
    }
}

这就是我的 RestDataConverter 的样子:

public class RestDataConverter<TSource, TDestination> : ITypeConverter<IRestData<TSource>, IRestData<TDestination>>
{
    public IRestData<TDestination> Convert(IRestData<TSource> source, IRestData<TDestination> destination, ResolutionContext context)
    {
        destination = destination ?? new RestData<TDestination>();
        destination.SetData(context.Mapper.Map<TDestination>(source.Data));
        destination.SetPaging(source.Paging);
        return destination;
    }
}

我正在尝试在两个特定对象类型的集合之间进行映射(来源:RestData>,dest:RestData>)。这是我的模型类型:

public class DocumentRecord
{
    public DateTime CreatedTs { get; set; }
    public int DocumentId { get; set; }
    public long FileSize { get; set; }
    public DateTime LastUpdatedTs { get; set; }
    public int NumberOfPages { get; set; }
    public string OriginalFileName { get; set; }
    public IList<PageGroupRecord> PageGroups { get; set; } = new List<PageGroupRecord>();
    public string Type { get; set; }
}

public class Document
{
    public int ConfigurationId { get; set; }
    public DateTime CreatedTs { get; set; }
    public int DocumentId { get; set; }
    public string FileLocation { get; set; }
    public int FileSize { get; set; }
    public DateTime LastUpdatedTs { get; set; }
    public int NumberOfPages { get; set; }
    public string OriginalFileName { get; set; }
    public IList<PageGroup> PageGroups { get; set; } = new List<PageGroup>();
    public string Type { get; set; }
}

这里是这两种对象类型的 AutoMapper.Profile:

public class ServicesProfile : Profile
{
    public ServicesProfile()
    {
        CreateMap<Document, DocumentRecord>()
            .ForMember(_ => _.Configuration, _ => _.Ignore())
            .ReverseMap();
    }
}

我正在 Startup.cs 中加载配置文件:

public void ConfigureServices(IServiceCollection services)
{
    var mapperConfiguration = new MapperConfiguration(_ =>
                                                    {
                                                        _.AddProfile<CommonProfile>();
                                                        _.AddProfile<ServicesProfile>();
                                                    });
    services.AddSingleton(mapperConfiguration);
    services.AddSingleton(mapperConfiguration.CreateMapper());
}

每当我做地图时,我都会遇到这个异常:

无法将“RestDataConverter`2[System.Collections.Generic.List`1[DocumentRecord],System.Collections.Generic.List`1[Document]]”类型的对象转换为“AutoMapper.ITypeConverter`2[ RestData`1[System.Collections.Generic.List`1[DocumentRecord]],RestData`1[System.Collections.Generic.List`1[Document]]]'。

此外,当我尝试做一些更简单的事情(来源:RestData,dest:RestData)例如这个单元测试时,我得到了类似的异常:

public class CommonProfileTests : BaseTests
{
    static CommonProfileTests()
    {
        Mapper.Initialize(m => m.AddProfile<CommonProfile>());
    }

    // This unit test passes
    [Fact]
    public void Configuration_Is_Valid() => AssertConfigurationIsValid();

    // This unit test fails with the error below
    [Fact]
    public void RestData_Maps_To_RestData_Correctly()
    {
        var source = new RestData<int>(1, new Paging(4));

        var destination = Map<RestData<int>>(source);

        Assert.Equal(source.Data, destination.Data);
    }
}

同样的基本例外:

无法将类型“RestDataConverter`2[System.Int32,System.Int32]”的对象转换为类型“AutoMapper.ITypeConverter`2[RestData`1[System.Int32],RestData`1[System.Int32]] '。

【问题讨论】:

    标签: c# generics automapper nested-generics open-generics


    【解决方案1】:

    我发现了问题所在。我的 RestDataConverter 使用的是接口类型而不是具体类型。当我改为使用具体的 RestData 时,它突然开始正常工作了。

    public class RestDataConverter<TSource, TDestination> : ITypeConverter<RestData<TSource>, RestData<TDestination>>
    {
        public RestData<TDestination> Convert(RestData<TSource> source, RestData<TDestination> destination, ResolutionContext context)
        {
            destination = destination ?? new RestData<TDestination>();
            destination.SetData(context.Mapper.Map<TDestination>(source.Data));
            destination.SetPaging(source.Paging);
            return destination;
        }
    }
    

    【讨论】:

    • 我也想知道你是否将你的接口标记为逆变的它会起作用。
    猜你喜欢
    • 2016-08-11
    • 2015-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-28
    • 2018-11-15
    • 2020-11-02
    相关资源
    最近更新 更多