2013-10-20 341 views
2

我有一個名爲ActionResult的實體,我的方法沿着應用程序返回。現在,我想它是在該對象的數組正確的位置映射在一個的ActionResult返回的對象......AutoMapper映射對象到數組

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

現在,你可以看到我想要做的是採取的是從返回的員工方法,並搜索Core中的Employees數組,並使用AutoMapper使用新的給定數據對其進行更新。

回答

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); 
+0

我想你提供了幫助但遺憾的是它不映射屬性休息... IDK的爲什麼 –

+0

@DanialEugen在第二個方法,如果你有核心的一些性質應被映射的話,我想您應該在類型轉換器中手動映射它們(因爲對象使用自定義類型轉換器映射)。員工的所有屬性都應該映射而​​沒有問題。 –