自动映射嵌套对象

时间:2017-02-28 22:56:20

标签: c# asp.net-web-api .net-core automapping

我有以下类结构

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;
}

上述层次结构的返回类型为

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

我想将员工类映射到EmployeeViewModel,其中Employee firstname和lastname将映射到employeeViewModel FullName属性。我可以通过以下代码来实现这一目标

public class EmployeeViewModel
{
    public FullName;
}


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

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

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

1 个答案:

答案 0 :(得分:6)

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

a)创建类源&amp;像这样的目的地类

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();

//您可以测试自动对象是否创建了预期的对象,在映射

之后添加以下代码
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"
            }
        }
    }
}