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 };
}
}
Automapper is considerably faster when mapping a List<T> of objects on . NET Core (It's still slower on full . NET Framework).
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With