1

I know this might be flagged as a duplicate question, and yes, I did review the questions that may already have answered my question, but still couldn't find an answer.

As most of the other questions relate to, my issue is related to models that reference each other. I am well aware of other approaches that I can follow, like refactoring my code to create separate DTO objects for the children. Problem is, there are quite allot of models and refactoring everything will be very cumbersome.

I read the Automapper v5.0 Upgrade Guide, which states the following:

enter image description here

Which I've tried - for example the ClientModel:

var clientModelMap = CreateMap<Client, ClientModel>()
    .ForMember(dest => dest.Id, source => source.MapFrom(x => x.ClientId))
    .ForMember(dest => dest.InvoicePayments, source => source.Ignore());

clientModelMap.MaxDepth(1);
clientModelMap.PreserveReferences();

as well as in the Project model:

var projectModelMap = CreateMap<Project, ProjectModel>()
    .ForMember(dest => dest.Client, source => source.Ignore())
    .ForMember(dest => dest.Id, source => source.MapFrom(x => x.ProjectId))
    .ForMember(dest => dest.ClientName, source => source.MapFrom(x => x.Client.ClientName))
    .ForMember(dest => dest.ClientTariff, source => source.MapFrom(x => x.Client.Tariff))
    ;
projectModelMap.MaxDepth(1);
projectModelMap.PreserveReferences();

The structure is as follows:

  • Client
    • Project (each client has many projects)
      • Resource (each project has a project manager)
        • Projects (is associated with one or more projects he/she is working on)
        • Client (is associated with a client / acts as the manager)

But this has no effect, and I still receive a StackOverflowException. What am I missing or doing wrong?

I'm open for suggestions, if this is not the way to go.

Many thanks!

Community
  • 1
  • 1
Richard Bailey
  • 2,658
  • 4
  • 27
  • 45
  • Can you set up a [MVCE](http://stackoverflow.com/help/mcve)? – stuartd Sep 01 '16 at 09:10
  • @stuartd - thanks for the response. I actually found my issue. The code examples provided by the v5.0 Guide functions correctly. The thing is I didn't implement it futher down in the model hierarchy. – Richard Bailey Sep 01 '16 at 09:35
  • Just to better understand `MaxDepth(x)`: it basically states the following. For each time it enters the mapping profile for the specified model being mapped, it will check whether the max has been reached. Thus if you could like a `Client` to reference a `Project` as well as a `User`, then you set it to 2. Is this correct? – Richard Bailey Sep 01 '16 at 09:40

1 Answers1

0

(Posted on behalf of the OP).

It's functioning as expected - I just needed to update mapping profiles on the rest of the model hierarchy.

halfer
  • 19,824
  • 17
  • 99
  • 186