0

How to create AutoMapper configuration when the source and destination classes are totally different ? I want to create a mapping between some external classes (which cannot be changed) and my classes which I'm gonna persist in the db. I could persist the entire external class , but I dont want to do that to save space. I'm using .net core 2.0.

For ex: I've an external class like below :

A
{
   B {
        b1;b2;b3;
   }
   C {
        c1;c2;c3;
   }
}

The above needs to be mapped to my class defined like below :

A
{
    Optmized_BC{ 
      b1;
      b2;
      c1;
    }
    c2;
}

What's the best way to create AutoMapper configuration in the above case ? Should I call CreateMap for every pair of source/destination variable ? Is there a way where I can map all variables inside one CreateMap call (using some clever linq maybe ?)

vinit
  • 501
  • 5
  • 15
  • I guess, you will find the idea of such mapping here https://stackoverflow.com/questions/21413273/automapper-convert-from-multiple-sources – yesenin Oct 21 '18 at 12:45
  • Isn't the purpose of automapper to map between two totally different classes? If they were the same class why would any mapping be necessary? – JSON Oct 22 '18 at 21:02

1 Answers1

0

You could persist your data as JSON in the database, then it would be easy to deserialize it to the other class using Newtonsoft JSON library. You have to decide if it's easier than writing the mapper function for each case. The same structure/naming would be deserialized automatically, otherwise, you could use 'dynamic'.

Just to give you an idea:

var result = JsonConvert.DeserializeObject<dynamic>(json);
A a = new A();
a.Optmized_BC.b1 = result.B.ToObject<B>().b1;

I would suggest to use the explicit mapper and cover it with the unit tests

VladL
  • 12,769
  • 10
  • 63
  • 83