2

I have an Entity that contains a dictionary, and what i want to achieve is that automapper not simply Replace the dictionary but updates it's values.

class ExampleClass
{
    public string Name { get; set; }
    public Dictionary<int, string[]> Dictionary { get; set; } 
}

Mapper.CreateMap<ExampleClass, ExampleClass>().ForAllMembers(opt => opt.Condition(srs => !srs.IsSourceValueNull));

var originalClass = new ExampleClass();
originalClass.Name = "Original Class";
originalClass.Dictionary = new Dictionary<int, string[]>
{
    {0, new []{"V1", "V2", "V3"}},
    {1, new []{"V1", "V2", "V3"}},
    {2, new []{"V1", "V2", "V3"}}
};

var newelyCreatedClass = new ExampleClass();
newelyCreatedClass.Dictionary = new Dictionary<int, string[]>
{
    {1, new []{"E1", "E2", "E9"}},
};

Mapper.Map(newelyCreatedClass, originalClass);

In the above code, automapper strangely doesn't update the Dictionary element with key == 1 but replaces the whole original one with the one created in newelyCreatedClass .

Roman Ratskey
  • 5,101
  • 8
  • 44
  • 67

1 Answers1

0

AutoMapper just automatically compares and sets values if they exist, this is why the property is getting overwritten. But what you can do is use an automapper feature called Custom Value Resolvers.

Then you could just write a resolver to check the dictionary and its values.

public class CustomResolver : IValueResolver<ExampleClass, ExampleClass, Dictionary<int, string[]>>
{
    public Dictionary<int, string[]> Resolve(ExampleClass source, ExampleClass destination, Dictionary<int, string[]> member, ResolutionContext context)
    {
        // logic to iterate through the dictionarys and resolve into dictionary containing values that you want.
    }
}
codeplay
  • 182
  • 1
  • 8