简体   繁体   中英

C# automapper nested object conditional map

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM