Automapper Convention

泄露秘密 提交于 2019-12-09 13:11:38

问题


Is is possible with Automapper to setup a convention so that maps do not have to be created by hand for situations where the entity you are mapping to just has say "ViewModel" appended.

As an example I would rather not have to setup the following map:

Mapper.CreateMap<Error, ErrorViewModel>();

I understand if projection is required that I would need to create a custom map, but having a convention to create maps would be nice.


回答1:


You would need to use Mapper.DynamicMap<TDest>(source) to map.

As you can see in the example below, it automatically maps the matching properties from source to destination.

using AutoMapper;
using System.Diagnostics;

class Program
{
    static void Main(string[] args)
    {
        var source = new Foo {Value = "Abc"};
        var destination = Mapper.DynamicMap<FooViewModel>(source);

        Debug.Assert(source.Value == destination.Value);
    }
}

public class Foo
{
    public string Value { get; set; }
}

public class FooViewModel
{
    public string Value { get; set; }
}


来源:https://stackoverflow.com/questions/2030227/automapper-convention

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