0

I have problem with automapper

Here I have two objects:

Object 1:

public class First
{
    ......

    public IList<string> ImportantList{ get; set; }

    ......
}

Object 2:

public class Second
{
    .....

    public IList<ImportantListClass> ImportantList{ get; set; }

    .....
}

class:

public class ImportantListClass
{
    public string Name{ get; set; }
}

I try to use automapper to map First object to Second but my destination ImportantList is Empty. I have the same number of object in destination class but Name property is null.

I try:

CreateMap<Second, First>()
            .ForMember(z => z.ImportantList, map => map.MapFrom(z => 
             z.ImportantList.Select(x => x.Name).ToList()))
            .ReverseMap();

But it not change anything Is their any better way to do this

@EDIT

I ADD this:

        CreateMap<First, Second>();
        CreateMap<ImportantListClass, string>()
            .ConvertUsing(source => source.Name);
        CreateMap<string, ImportantListClass>()
                .ForMember(z => z.Name, z=> z.MapFrom(d => d));

Thanks for help!

1

1 Answer 1

2

You need to use ConvertUsing and add a map from ImportantListClass to string:

var config = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<Second, First>();
    cfg.CreateMap<ImportantListClass, string>()
    .ConvertUsing(source => source.Name);
});

var mapper = config.CreateMapper();

var second = new Second
{
    Id = 22,
    ImportantList = new List<ImportantListClass>
    {
        new ImportantListClass { Name = "Name1" },
        new ImportantListClass { Name = "Name2" }
    }
};

var first = mapper.Map<First>(second);
Sign up to request clarification or add additional context in comments.

2 Comments

d should be source :)
@LucianBargaoanu no problem, I modified the parameter name

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.