5

我使用自动映射器。我有两个类:具有单一属性的 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 };
    }
}
4

1 回答 1

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
于 2012-10-16T06:51:31.110 回答