自动映射:数组到对象映射

时间:2014-01-27 10:14:20

标签: c# mapping 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());

这是我的整个程序,我尝试不同的方式,但我得到了errros。

2 个答案:

答案 0 :(得分:3)

我用这段代码解决了这个问题。

映射:

 CreateMap<HealthView, HealthResponse.HealthLine>();

在控制器中:

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

答案 1 :(得分:2)

我认为你想将HealthView映射到HealthLine,所以试试这个:

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