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 };
}
}
You can use one of the
ConstructUsingoverloads to tell AutoMapper which constructor should it useAs an alternative solution you can create your
TypeBby hand the AutoMapper can fill in the rest of the properties”: