Skip to content

How to map from Dictionary<string, object> to Class Case-Insensitive? #3243

@drmcclelland

Description

@drmcclelland

Using AutoMapper 9 with a .NET Core 2.2 console app, I have replicated an issue we have with case-sensitivity when mapping from a Dictionary<string, object> to a C# class.

Per the docs, you can map straight from Dictionary<string, object> to objects, AutoMapper will line up the keys with property names.

However, this seems to be case-sensitive, because in my example below, the dictionary key "ID" is not being mapped to the property name "Id".

What configuration do I need to make this mapping to be case-insensitive?

    class Program
    {
        public class Person
        {
            public int Id { get; set; }
            public string Name { get; set; }
        }

        static void Main(string[] args)
        {
            var config = new MapperConfiguration(cfg => {});

            var mapper = config.CreateMapper();

            var good = new Dictionary<string, object>
            {
                {"Id", 123 },
                {"Name", "John Doe" },
            };

            var bad = new Dictionary<string, object>
            {
                {"ID", 456 },
                {"Name", "Jane Doe" },
            };

            var personGood = mapper.Map<Person>(good);
            var personBad = mapper.Map<Person>(bad);

            Debug.Assert(personGood.Id == 123);
            Debug.Assert(personGood.Name == "John Doe");

            Debug.Assert(personBad.Id == 456);    // This assertion fails since personBad.Id == 0
            Debug.Assert(personBad.Name == "Jane Doe");
        }
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions