Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper Convention

Tags:

c#

automapper

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.

like image 378
beckelmw Avatar asked Jan 08 '10 19:01

beckelmw


1 Answers

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; }
}
like image 61
Dominik Fretz Avatar answered Sep 28 '22 09:09

Dominik Fretz