0
votes

Using AutoMapper, I'm trying to map two types that I pull from two different assemblies via reflection. However, when working with Types, I am unable to get the .ForMember() method to ignore any members that I specify. The regular lambda syntax does not compile because the member name is not found on the Type type of the class. Passing in a string of the member allows compilation, but still does not ignore the member. Using config.AssertConfigurationIsValid() shows that this is an invalid configuration.

class ExampleSchema
{
    public int Age {get; set;}
}

class ExampleDto
{
    public int Age {get; set;}
    public int Weight {get; set;}
}

In the code that reflects over the above assemblies:

var schemaType = typeof(ExampleSchema);
var dtoType = typeof(ExampleDto);

// This will throw
// Cannot convert lambda expression to string because it is not a delegate type
cfg.CreateMap(schemaType, dtoType)
    .ForMember(dest => dest., opt => opt.Ignore());

// Hard-code cringing aside, this still does not filter out the member
cfg.CreateMap(schemaType, dtoType)
    .ForMember("Weight", opt => opt.Ignore());  

Is this a bug in AutoMapper or am I just using the method incorrectly?

2
I did not see any problem with your code (except the part with the lambda, but that is obvious). I also tested it and it was no problem to map ExampleSchema instance to ExampleDto instance. - Sir Rufo
What version are you using? - Jimmy Bogard
The very latest 5.1.1 - Sir Rufo
I am on latest, 5.1.1 - Dagrooms

2 Answers

1
votes

I wrote a small test to see what is happening

        [TestMethod]
    public void TestMethod3()
    {
        var schemaType = typeof(ExampleSchema);
        var dtoType = typeof(ExampleDto);

        MapperConfiguration config = new MapperConfiguration(cfg =>
        {
            cfg.CreateMap(schemaType, dtoType)
                .ForMember("Weight", conf => conf.Ignore());
        });

        config.AssertConfigurationIsValid();

        var mapper = config.CreateMapper();

        var schema = new ExampleSchema { Age = 10 };

        var dto = mapper.Map<ExampleDto>(schema);

        Assert.AreEqual(dto.Age, 10);
        Assert.AreEqual(dto.Weight, 0);
    }

And it is green. You don't even need to configure anything.

0
votes

Make your properties public and use

cfg.CreateMap<ExampleSchema, ExampleDto>()

. Then you will have an access to ForMember overload that accepts Expression parameter.