自动映射器映射嵌套对象

Automapper mapping nested objects

我有以下 classes 结构

public class ClassA
{
    public ClassB objB;
}

Public class ClassB
{
    public ListOfData objListofData;
}

public class ListOfData 
{
    public Employee objEmp;
}

public class Employee
{
    public string FirstName;
    public string LastName;
}

Return 以上层次结构的类型为

"ClassA":{
    "classB":{
        "ListOfData":{
            "employee":{
                "FirstName":"David",
                "LastName" :"Peter"
            }
        }
    }
}

我想将员工 class 映射到 EmployeeViewModel,其中员工的名字和姓氏将映射到 employeeViewModel 全名 属性。我可以通过以下代码

来实现
public class EmployeeViewModel
{
    public FullName;
}


CreateMap<Employee,EmployeeViewModel>()
                         .ForMember(dest => dest.FullName,
                                    opts => opts.MapFrom(
                                        src => string.Format("{0} {1}",
                                        src.FirstName, src.LastName)));

现在我如何 return 返回原始 class具有 EmployeeViewModel 映射的对象。像这样的东西 ??

"ClassA":{
    "classB":{
        "ListOfData":{
            "EmployeeViewModel":{
                "FullName":"David Peter"
            }
        }
    }
}

在花了很多时间阅读文档之后,我发现这里的解决方案就是我的方法

a)像这样Class创建源和目标类

public class ClassA
{
    public ClassB objB;
}

Public class ClassB
{
    public ListOfData objListofData;
}

public class ListOfData 
{
    public Employee objEmp;
}

public class Employee
{
    public string FirstName;
    public string LastName;
}
------------------------------------
public class DestClassA
{
    public DestClassB objB;
}

Public class DestClassB
{
    public DestListOfData objListofData;
}

public class DestListOfData 
{
    public DestEmployee objEmp;
}

public class EmployeeViewModel
{
    public string FullName;
}

b)创建映射

var config = new MapperConfiguration(cfg => {

    cfg.CreateMap<Employee, EmployeeViewModel>().
                ForMember(dest => dest.FullName, opts => opts.MapFrom(
                    src => string.Format("{0} - {1}",
                    src.FirstName, src.LastName)));
    cfg.CreateMap<ListOfData, DestListOfData>();
    cfg.CreateMap<GetFundFamilyOutOfBalanceTotalsResponse, GetFundFamilyOutOfBalanceTotalsResponseMapped>();
    cfg.CreateMap<ClassB, DestClassB>();
    cfg.CreateMap<ClassA, DestClassA>();
});

//这是为了确保你的映射是正确的

config.AssertConfigurationIsValid();

//可以测试expected objected是否是automapper创建的,映射后添加如下代码

var mapper = config.CreateMapper();
var output = new ClassA
{
    objClassB = new ClassB
    {
        objListofData = new ListOfData 
        {
            Employee = new []
               {
                    new Employee  { FirstName = "David", LastName ="Peter" }
               }
        }
    }
};

var destMap = mapper.Map<DestClassA>(output);

//如果你探索这个对象你会发现像这样的对象结构

"ClassA":{
    "classB":{
        "ListOfData":{
            "EmployeeViewModel":{
                "FullName":"David Peter"
            }
        }
    }
}