如何将上下文值传递给Automapper Map?

时间:2012-10-16 06:05:01

标签: c# configuration map automapper

我使用Automapper。 我有两个类:具有单个属性的TypeA; TypeB有两个属性,其中一个有私有的setter,这个属性的值是通过构造函数传递的。 TypeB没有默认构造函数。

问题:是否可以配置Automapper将TypeA转换为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 };
    }
}

1 个答案:

答案 0 :(得分:8)

您可以使用其中一个ConstructUsing重载来告诉AutoMapper它应该使用哪个构造函数

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

作为替代解决方案,您可以手动创建TypeB,AutoMapper可以填写其余属性“:

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