Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass context values to Automapper Map?

I using Automapper. I have two classes: TypeA with single property; TypeB with two properties, one of them have private setter and value for this property is passed via constructor. TypeB have no default constructor.

Question: is it possible to configure Automapper to convert TypeA to TypeB.

public class TypeA
{
    public string Property1 { get; set; }
}

public class TypeB
{
    public TypeB(int contextId)
    { ContextId = contextId; }

    public string Property1 { get; set; }

    public int ContextId { get; private set; }
}

public class Context
{
    private int _id;

    public void SomeMethod()
    {
        TypeA instanceOfA = new TypeA() { Property1 = "Some string" };

        // How to configure Automapper so, that it uses constructor of TypeB 
        // and passes "_id" field value into this constructor?

        // Not work, since "contextId" must be passed to constructor of TypeB
        TypeB instanceOfB = Mapper.Map<TypeB>(instanceOfA);

        // Goal is to create folowing object
        instanceOfB = new TypeB(_id) { Property1 = instanceOfA.Property1 };
    }
}
like image 693
Andris Avatar asked Oct 16 '12 06:10

Andris


People also ask

Is AutoMapper faster than manual mapping?

Automapper is considerably faster when mapping a List<T> of objects on . NET Core (It's still slower on full . NET Framework).

When should you not use AutoMapper?

If you have to do complex mapping behavior, it might be better to avoid using AutoMapper for that scenario. Reverse mapping can get very complicated very quickly, and unless it's very simple, you can have business logic showing up in mapping configuration.

What can I use instead of AutoMapper?

AutoMapper is one of the popular object-object mapping libraries with over 296 million NuGet package downloads. It was first published in 2011 and its usage is growing ever since. Mapster is an emerging alternative to AutoMapper which was first published in 2015 and has over 7.4 million NuGet package downloads.


1 Answers

You can use one of the ConstructUsing overloads to tell AutoMapper which constructor should it use

TypeA instanceOfA = new TypeA() { Property1 = "Some string" };
_id = 3;            

Mapper.CreateMap<TypeA, TypeB>().ConstructUsing((TypeA a) => new TypeB(_id));    
TypeB instanceOfB = Mapper.Map<TypeB>(instanceOfA);

// instanceOfB.Property1 will be "Some string"
// instanceOfB.ContextId will be 3

As an alternative solution you can create your TypeB by hand the AutoMapper can fill in the rest of the properties":

TypeA instanceOfA = new TypeA() { Property1 = "Some string" };
 _id = 3;            

Mapper.CreateMap<TypeA, TypeB>();

TypeB instanceOfB = new TypeB(_id);
Mapper.Map<TypeA, TypeB>(instanceOfA, instanceOfB);

// instanceOfB.Property1 will be "Some string"
// instanceOfB.ContextId will be 3
like image 163
nemesv Avatar answered Sep 20 '22 13:09

nemesv