0

I'm using .Net Core with latest automapper version and I've a question on nested objects.

I've a view model like below (This I can't change as its a 3rd party one):

public class MyTempA
{ 
    string ShapeName;
    object ShapeDetails;
    //....some other props
}

I've db classes and view models for below

  1. Square (DB Entity)
  2. SquareViewModel
  3. Pyramid (DB Entity)
  4. PyramidViewModel
  5. Cylinder (DB Entity)
  6. CylinderViewModel

I've individual mappers existing for above DB entities to view models.

My question: ShapeDetails object in MyTempA can be any of the view models based on ShapeName. How can I map that using Automapper?

If ShapeName is Square, ShapeDetails should be SquareViewModel (mapped from Square db class).

Thanks

1 Answer 1

2

There are two options you could use:

The first one is to use the mapping inheritance feature provided by AutoMapper if your classes have a base class.

https://docs.automapper.org/en/stable/Mapping-inheritance.html

As a second option you could write a custom value resolver:

https://docs.automapper.org/en/stable/Custom-value-resolvers.html

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks v much. I dont have a base class so I have to go through second option. I am going through articles for Custom Value Resolver but they are showing only for static properties (like int, decimal...), I dont see a mapper/ViewModel returned. Do you have any example link?
Here is a basic example of how it could look lile: gist.github.com/NQuirmbach/df606e2b32cedfd3e3f847a4bf81769e

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.