AutoMapper将对象映射到数组

时间:2013-10-20 21:16:08

标签: c# automapper

我有一个名为ActionResult的实体,我的应用程序返回的方法。现在我想将ActionResult中返回的对象映射到该对象数组中的正确位置...

public class Core
{
    public Employee[] Employees = new[] {
        new Employee {
            Name = "Jack",
            Age = 21,
            Salary = 1000
        },
        new Employee {
            Name = "Carl",
            Age = 35,
            Salary = 1000
        }, 
        new Employee {
            Name = "Tom",
            Age = 41,
            Salary = 1000
        }, 
    };
}

public class ActionResult
{
    public string ActionID { get; set; }
    public Employee Employee { get; set; }
}

public class Employee
{
    public String Name { get; set; }
    public int? Age { get; set; }
    public int? Salary { get; set; }
    public int? Level { get; set; }
}

public ActionResult MethodThatReturnsActionResultWithAnEmployee()
{
    return new ActionResult {
        ActionID = new Guid().ToString(),
        Employee = new Employee {
            Name = "Carl",
            Age = 35,
            Salary = 7000,
            Level = 1
        }
    };
}

现在您可以看到我想要做的是从Method返回的Employee,并在Core中的Employees数组中搜索并使用AutoMapper使用新的给定数据更新它。

1 个答案:

答案 0 :(得分:2)

AutoMapper不会为您搜索某些阵列中的员工。如何知道哪些员工应该被视为平等?您应该手动搜索员工,并使用适当的映射方法使用来自其他员工实例的数据更新现有员工实例:

Mapper.CreateMap<Employee, Employee>();
var result = MethodThatReturnsActionResultWithAnEmployee();
var employee = result.Employee;
var core = new Core();
var employeeToUpdate = 
    core.Employees.FirstOrDefault(e => e.Name == employee.Name);
Mapper.Map(employee, employeeToUpdate);

如果你真的想要映射看起来像

Mapper.Map(result, core);

然后你应该为此编写自己的类型映射器:

public class ActionResultToCoreConverter : ITypeConverter<ActionResult, Core>
{
    public Core Convert(ResolutionContext context)
    {
        var result = (ActionResult)context.SourceValue;
        var employee = result.Employee;
        var core = (Core)context.DestinationValue ?? new Core();
        var employeeToUpdate = 
            core.Employees.FirstOrDefault(e => e.Name == employee.Name);
        Mapper.Map(employee, employeeToUpdate);
        return core;
    }
}

映射将如下所示:

Mapper.CreateMap<Employee, Employee>(); // this map also required
Mapper.CreateMap<ActionResult, Core>()
      .ConvertUsing<ActionResultToCoreConverter>();

var result = MethodThatReturnsActionResultWithAnEmployee();
var core = new Core();
Mapper.Map(result, core);
// if you want to create new Core instanse:
var core2 = Mapper<Core>(result);