-2

I have two source object:

public class Book
{
    public int Id {get;set;}
    public IList<Unity> Unities {get;set;}
}

public class Unity
{
    public int Id {get;set;}
    public string Title {get;set;}
}

and three destination object:

public class DtoBook
{
    public int Id {get;set;}
    public DtoOrganization Organization {get;set;}
}

public class DtoOrganization
{
    public int Id {get;set;}
    public IList<DtoUnity> Unities {get;set;}
}

public class DtoUnity
{
    public int Id {get;set;}
    public string Title {get;set;}
}

I'd like to map the two source objects Book and Unity to the three dto objects but doesn't exist an Organization source object. How can I do it with Automapper?

Thanks!!!

Post my actual code Automapper code:

public static void Configure()
{
    Mapper.Reset();

    Mapper.CreateMap<Unity, Model.Organization>();

    Mapper.CreateMap<Book, Model.Manifest>()
            .ForMember(x => x.Version, y => y.UseValue("1.1"));                

    Mapper.AssertConfigurationIsValid();
}

public static Model.Manifest Map(Book book)
{
    Configure();
    Model.Manifest dtoManifest = Mapper.Map<Book, Model.Manifest>(book);
    return dtoManifest;
}
Cisco Cabe
  • 584
  • 5
  • 10

1 Answers1

0

If I didn't miss anything this could look like this (it's a easy way if you don't want to learn how AutoMapper works):

class Program
{
    static void Main(string[] args)
    {
        var sampleBook = new Book { 
            Id = 1, 
            Unities = new List<Unity> { 
                new Unity { Id = 2, Title = "Title of unity" }, 
                new Unity { Id = 3, Title = "Title of unity" } 
            } 
        };

        var ourBookDto = new DtoBook
        {
            Id = sampleBook.Id,
            Organization = new DtoOrganization
            {
                Id = 666, // i don't know from where do you want to obtain this id
                Unities = sampleBook.Unities.Select(u => new DtoUnity { 
                    Id = u.Id,
                    Title = u.Title
                }).ToList()
            }
        };

        Console.ReadLine();
    }
}

But this may be a little dirty if your classes become more complex so instead try to use AutoMapper.

rosko
  • 464
  • 3
  • 16