Nikunj B. Balar
Nikunj B. Balar

Reputation: 298

Automapper: Array to Object mapping

I have one proble for creating mapping from array to object type. so anybody have a answer for this then please help me.

view model (Source class) :

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

converted in this (Destination Class):

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

mapping :

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

This is my whole procedure, i try to different way but i got errros.

Upvotes: 1

Views: 4334

Answers (2)

Nikunj B. Balar
Nikunj B. Balar

Reputation: 298

I have solved this problem with this code.

Mapping :

 CreateMap<HealthView, HealthResponse.HealthLine>();

In Controller :

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

Upvotes: 3

Gruff Bunny
Gruff Bunny

Reputation: 27976

I take it that you want to map a HealthView to a HealthLine so try this:

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

Upvotes: 2

Related Questions