Mapping service DTO to domain DTO

Hello,

I was wondering if ConvertTo can map complex objects. I have the following scenario: I have a service DTO that contains a few properties including a List<SomeClass> that I would like to convert to my domain type which has the same structure however SomeClass is in a different namespace. The conversion copies the value types without issues however the list is not copied. I would have expected ConvertTo to copy the list as well.

Is this a limitation of the convert method?

I’m using 4.5.4 but I can reproduce it in 4.5.14. You can find code that reproduce the issue below:


using System;
using System.Collections.Generic;
using ServiceStack;

namespace ConsoleApplication7
{
    class Program
    {
        static void Main(string[] args)
        {
            var serviceCart = new Stuff.ServiceModel.Cart() { Id = 38 };
            serviceCart.LineItems.Add(new Stuff.ServiceModel.LineItem() { Id1 = Guid.NewGuid() });

            var entitiesCart = serviceCart.ConvertTo<Stuff.Entities.Cart>();

            Console.WriteLine($$"ServiceModel cart line item count: {serviceCart.LineItems.Count}");
            Console.WriteLine($$"Entities cart line item count: {entitiesCart.LineItems.Count}");
        }
    }
}

namespace Stuff.ServiceModel
{
    public class Cart
    {
        public int Id { get; set; }
        public List<LineItem> LineItems { get; set; } = new List<LineItem>();
    }

    public class LineItem
    {
        public Guid Id1 { get; set; }
        public Guid Id2 { get; set; }
        public DateTime NextOccurence { get; set; }
    }
}

namespace Stuff.Entities
{
    public class Cart
    {
        public int Id { get; set; }
        public List<LineItem> LineItems { get; set; } = new List<LineItem>();
    }

    public class LineItem
    {
        public Guid Id1 { get; set; }
        public Guid Id2 { get; set; }
        public DateTime NextOccurence { get; set; }
    }
}



No it doesn’t automatically map nested collections which we recommend to do in extension methods, e.g:

var entitiesCart = serviceCart.FromDto();

public static class ConvertExtensions
{
    public static Cart ToDto(this Entities.Cart from)
    {
        var to = from.ConvertTo<Cart>();
        to.LineItems = from.LineItems.Map(x => x.ConvertTo<LineItem>());
        return to;
    }

    public static Entities.Cart FromDto(this Cart from)
    {
        var to = from.ConvertTo<Entities.Cart>();
        to.LineItems = from.LineItems.Map(x => x.ConvertTo<Entities.LineItem>());
        return to;
    }
}

Thanks for the link.