AutoMapper generic conversion

会有一股神秘感。 提交于 2020-05-27 11:49:05

问题


I've been using AutoMapper and would like to take generic conversion one step further; instead of saying something like

cfg.CreateMap<Container<int>, int>()
    .ConvertUsing(new ContainerConverter<Container<int>, int>());

I would rather set the AutoMapper to know how to map any Container, such as:

cfg.CreateMap<Container<T>, T>()
    .ConvertUsing(new ContainerConverter<Container<T>, T>());

Since all conversions from Container to T are the same, it would be pointless to re-define this conversion for all of the classes I am converting.


回答1:


Create your own map method as a generic, here is a basic example that you could modify as needed

/// <summary>
/// Maps one object into a new object of another type
/// </summary>
public static TResult Map<TSource, TResult>(this TSource source)
    where TSource : class
    where TResult : class, new()
{
    var ret = new TResult();
    source.Map(ret);
    return ret;
}

/// <summary>
/// Maps one object into an existing object of another type
/// </summary>
public static void Map<TSource, TResult>(this TSource source, TResult destination)
    where TSource : class
    where TResult : class
{
    if (Mapper.FindTypeMapFor<TSource, TResult>() == null)
        Mapper.CreateMap<TSource, TResult>();
    Mapper.Map(source, destination);
}


来源:https://stackoverflow.com/questions/40287029/automapper-generic-conversion

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