0

I have two classes

 public class SourceClass
{
    public Guid Id { get; set; }
    public string Provider { get; set; }
}


public class DestinationClass
{
    public Guid Id { get; set; }
    public List<string> Provider { get; set; }
}

My mapping is as follows:

CreateMap<SourceClass, DestinationClass>()
    .ForMember(destinationMember => destinationMember.Provider,
        memberOptions => memberOptions.MapFrom(src => 
            new List<string> { src.Provider ?? "" }));

Now, previously Provider in the DestinationClass was Providers and the mapping worked as normal. However, after making the spelling in both classes consistent, the mapping fails to happen properly.

"Test" from Source class maps to ["T", "e", "s", "t"]. When the property names were different in each class, the mapping worked correctly.

4
  • Could possibly be Automapper trying to do this by convention? I was one that commented on your original question. Any particular reason for the rename from Providers to Provider? Commented Mar 10, 2020 at 4:05
  • @TylerHundley thanks for replying! I ended up using the solution you provided. The original name was "Provider" for both and I renamed to Providers as a workaround. However, I'd like to try and change it back to what it was originally Commented Mar 10, 2020 at 4:09
  • Is there a reason that the property is a list? If it isn't always a single item I think its clearer when defined as plural Commented Mar 10, 2020 at 4:44
  • Upgrade AutoMapper. Commented Mar 10, 2020 at 5:44

1 Answer 1

1

I've used:

  • Console Application
  • .NET 4.6.1
  • the latest stable Automapper

Such behaviour is not reproducible:

static MapperConfiguration _conf;

static void Main(string[] args)
{
    var src = new SourceClass() { Id = Guid.NewGuid(), Provider = "FooProvider" };
    InitializeAutomapper();
    var mapper = _conf.CreateMapper();
    DestinationClass destinationClass = mapper.Map<DestinationClass>(src);
    Console.WriteLine(destinationClass.Provider[0]);
}

static void InitializeAutomapper()
{
    _conf = new MapperConfiguration(cfg => 
        cfg.CreateMap<SourceClass, DestinationClass>()
            .ForMember(destinationMember => destinationMember.Provider,
                memberOptions => memberOptions.MapFrom(src => 
                    new List<string> { src.Provider ?? "" })));
}

Output:

FooProvider
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.