tags:

views:

180

answers:

0

If I have a one-to-many relationship and I want to transorm this into a list of flat Dto-s where some attributes of parent and some of child appear in a dto, is this something that is supported out-of-box with AutoMapper? For example if I have something like this

Parent

1. ParentId
2. ParentAttr1
3. List<Child>

Child

1. ChildId
2. ChildAttr1
2. ChildAttr2

Dto

1. ParentId
2. ChildId
2. ChildAttr1
3. ChildAttr2

How do I project Parent into a Dto where for each child in parent I will get an instace of Dto?

I've setup two maps Parent->Dto and Child->Dto but just doing _mapper.Map(parentInstance) only projects parents attributes. Does this have to be done in two steps, where I would iterate children myself?

One option is like this:

List viewModel = new List();

        foreach (var bp in mktgPlan.AllowedBaseProducts)
        {
            var baseProduct = bp;

            foreach (var cip in baseProduct.CoInsurancePercentages)
            {
                var coInsurance = cip;

                var dto = _mapper.Map<MarketingPlanBaseProduct, CoInsuranceDto>(baseProduct);

                _mapper.Map(coInsurance, dto);

                viewModel.Add(dto);
            }
        }

Other option if relationship is bi-directional would be to select all children and than map children only like this:

 var coInsurances = mktgPlan.AllowedBaseProducts.SelectMany(x => x.CoInsurancePercentages);

            var viewModel =
                _mapper.Map<IEnumerable<BaseProductCoInsurance>, List<CoInsuranceDto>>(coInsurances;

related questions