2014-01-27 175 views
1

我有一個創建從數組映射到對象類型的問題。所以任何人都有這個答案,那麼請幫助我。Automapper:陣列到對象映射

視圖模型(來源類):

public class HealthView : IView 
{ 
    public Guid Id { get; set; } 
    public string Type { get; set; } 
    public string Value { get; set; } 

    [JsonIgnore] 
    public DateTime? HealthCheckDateTime { get; set; } 
    public string HealthCheckDateTimeString { get { return HealthCheckDateTime.GetValueOrDefault().ToString(CultureInfo.InvariantCulture); } } 
} 

在此(目標類)轉化:

public class HealthResponse : WebApiResonseBase 
{ 
    public HealthResponse() 
    { 
     Value = new HealthLine[0]; 
    } 

    public HealthLine[] Value { get; set; } 

    public class HealthLine 
    { 
     public Guid Id { get; set; } 
     public string Type { get; set; } 
     public string Value { get; set; } 
     public DateTime? HealthCheckDateTime { get; set; } 
     public string HealthCheckDateTimeString { get; set; } 
    } 
} 

映射:

CreateMap<HealthView[], HealthResponse>() 
      .ForMember(x => x.RedirectRequired, o => o.Ignore()) 
      .ForMember(x => x.Uri, o => o.Ignore()); 

這是我的整個過程中,我嘗試以不同的方式,但我得到了錯誤。

+0

你到底想達到什麼目的? –

+0

我已經解決了這個問題。但是我的身邊出現了一些問題。所以我會在稍後給出答案。 –

+0

我正在嘗試數組映射到使用automapper的對象成員映射.. –

回答

3

我已經解決了這個問題,此代碼。

映射:

CreateMap<HealthView, HealthResponse.HealthLine>(); 

在控制器:

var response = new HealthResponse 
     { 
      Value = healthView.Select(Mapper.Map<HealthView, HealthResponse.HealthLine>).ToArray() 
     }; 
2

我認爲你要映射HealthView到健康熱線所以試試這個:

CreateMap<HealthView, HealthView>(); 

var response = new HealthResponse(); 
var views = an array of HealthView objects from somewhere. 

response.Value = Mapper.Map<IEnumerable<HealthView>,IEnumerable<HealthLine>>(views); 
+0

感謝您的幫助。 –