简体   繁体   中英

Automapper Convention

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.

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; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM