AutoMapper ignore member failing when mapping with Type objects

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?


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.


Make your properties public and use

cfg.CreateMap<ExampleSchema, ExampleDto>()

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

链接地址: http://www.djcxy.com/p/37414.html

上一篇: 使用AutoMapper将复杂对象展平为多个展平对象

下一篇: 与类型对象映射时,AutoMapper会忽略成员失败