Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# automapper dictionary to dictionary [duplicate]

I am trying to auto-map a Superhero model to a a Supervillan model, each has a similar dictionary declaration:

Superhero:

public class Superheroes {
    public Dictionary<string, SomeHero>> SuperNumber {get; set;}
}

public class SomeHero {
 // unique properties
}

Supervillan:

public class Supervillans {
    public Dictionary<string, SomeVillan>> SuperNumber {get; set;}
}

public class SomeVillan {
 // unique properties
}

I tried following the advice in other similar threads, but haven't been successful. Here is my latest attempt, that fails on execution:

CreateMap<KeyValuePair<string, Superheroes>, KeyValuePair<string, Supervillans>>(); 

How can I map my Superhero SuperNumber dictionary to my Supervillan SuperNumber dictionary?

Note: the SomeHero/SomeVillan models will have unique properties, but I'm not concerned with them for this question.

like image 931
Edon Avatar asked Feb 22 '19 22:02

Edon


1 Answers

It should work out of the box. Dictionaries don't require mappings to be explicitly configured: Dynamic and ExpandoObjects. Same for the classes if the properties are identical as in my examples.

public class ObjA
{ 
    public string Name { get; set; }
}

public class ObjB
{
    public string Name { get; set; }
}

public class ClassA
{
    public Dictionary<string, ObjA> Vals { get; set; } = new Dictionary<string, ObjA>{
        {"a", new ObjA(){ Name = "A", } },
        {"b", new ObjA(){ Name = "B", } },
        {"c", new ObjA(){ Name = "C", } },
        {"d", new ObjA(){ Name = "D", } },
    };
}

public class ClassB
{
    public Dictionary<string, ObjB> Vals { get; set; } = new Dictionary<string, ObjB>{
        {"a", new ObjB(){ Name = "A", } },
        {"b", new ObjB(){ Name = "B", } },
        {"c", new ObjB(){ Name = "C", } },
        {"d", new ObjB(){ Name = "D", } },
    };
}

If you then use the automapper as below, the mappings should work automagically.

var obja = new ClassA();
var objb = new ClassB();
var config = new MapperConfiguration(cfg => {});
var mapper = config.CreateMapper();
var obj = mapper.Map<ClassB>(obja);
var obj2 = mapper.Map<ClassA>(objb);

If you want to hard-code the mappings for the classes this should do it:

var config = new MapperConfiguration(cfg => {
    cfg.CreateMap<ClassA, ClassB>().ReverseMap();
});
like image 110
Timothy Jannace Avatar answered Nov 07 '22 12:11

Timothy Jannace