0

I have two data models, one for database and one for viewmodels like

public class ModelA{
    string name {get;set;}
}

public class ModelB{
    ModelA Parent;

    ModelB(ModelA parent){
        Parent = parent;
   }
}

And the ViewModel Models are the same

public class ViewModelA{
    string name {get;set;}
}

public class ViewModelB{
    ViewModelA Parent;
    IMapper map;
    ViewModelB(ViewModelA parent, IMapper _map){
        Parent = parent;
        map = _map;
   }
}

Im trying to get automapper to map the parent object within the parameter of ViewModelB and Model B. But everything I have tried is failing or I can only create new instances of the parent object (using ConstructUsing), not map the one in the constructor.

This is my profile for the above at the moment

public ModelBProfile:Profile{
     CreateMap<ModelB, ViewModelB>()
                    .ForMember(m => m.Parent, opt => opt.MapFrom(p => p.Parent));
}

I have been using a unity container and WPF and Prism. When the view of ViewModel A is navigated to, then Unity successfully injects the parent class (of which there is one instance). I also use Unity to store the AutoMapper instance. Which I then need in the viewmodel to map objects later.

Jack
  • 131
  • 1
  • 9
  • I'm currently a little outdated with AutoMapper but you can try [this](http://stackoverflow.com/a/34291059/6666799), [this](http://stackoverflow.com/a/5420874/6666799) or [this](http://stackoverflow.com/a/2239647/6666799) – Rabban Apr 03 '17 at 12:10
  • @Rabban thanks for your help, i solved my issues with this .PreserveReferences().ConstructUsing((league, context) => new LeagueModel(context.Mapper)) – Jack Apr 03 '17 at 14:37

1 Answers1

0

I had to change my viewmodel slightly and removed the parent from the constructor.

I resolved the mapper issue by including the Constructusing in my profile like such:

public Profile()
{
            CreateMap<ModelB, ViewModelB>()
                .PreserveReferences().ConstructUsing((a, context) => new ViewModelB(context.Mapper))
                .ForMember(c => c.Parent, opt => opt.MapFrom(s => s.Parent))
                c.Players));
}
Jack
  • 131
  • 1
  • 9