使用Type对象

时间:2016-10-27 15:20:12

标签: c# reflection automapper

使用AutoMapper,我试图通过反射映射我从两个不同的程序集中提取的两种类型。但是,在使用Types时,我无法使.ForMember()方法忽略我指定的任何成员。常规lambda语法无法编译,因为在类的Type类型上找不到成员名称。传入成员的字符串允许编译,但仍然不会忽略该成员。使用config.AssertConfigurationIsValid()显示这是一个无效的配置。

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

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

在反映上述程序集的代码中:

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());  

这是AutoMapper中的错误还是我只是错误地使用该方法?

2 个答案:

答案 0 :(得分:1)

我写了一个小测试来看看发生了什么

        [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);
    }

它是绿色的。你甚至不需要配置任何东西。

答案 1 :(得分:0)

公开您的财产并使用

cfg.CreateMap<ExampleSchema, ExampleDto>()

。然后,您将可以访问接受Expression参数的ForMember重载。

相关问题