首页 > 解决方案 > Automapper along with generics and mapping missing properties

问题描述

I'm trying to use a generic mapper for mapping two objects. So I have setup Automapper in this way which comes from the documentation:

        var config = new MapperConfiguration(cfg =>
        {
            cfg.CreateMap(typeof(Source<>), typeof(Destination<>));
        });
        mapper = config.CreateMapper();

Now everything works well in the case if the source and destination have the same properties and if I'm going from more properties on the source side to less properties on the destination. However if the source has less properties than the destination than I get an error:

Value ---> AutoMapper.AutoMapperConfigurationException: Unmapped members were found. Review the types and members below.

My question is there a way I could ignore these properties even though I won't know what they are at compile time?

Source:

 public class Source<T>
{
    public T Value { get; set; }
}

 public class Destination<T>
{
    public T Value { get; set; }
}


public class DataObject1
{
    public int Id { get; set; }
    public string Code { get; set; }
}

public class DataObject2
{
    public int Id { get; set; }
    public string Code { get; set; }
    public string ActiveFlag { get; set; }
}

Here is my Test Code:

        var data = new DataObject1() { Id = 10, Code = "Test" };

        var source = new Source<DataObject1> { Value = data };
        var dest = mapper.Map<Source<DataObject1>, Destination<DataObject2>>(source);

        Assert.AreEqual(dest.Value.Id, 10);

标签: c#automapper

解决方案


如果您像这样配置映射器时映射DataObject1到,您的映射将成功:DataObject2

var config = new MapperConfiguration(cfg =>
{
    cfg.CreateMap(typeof(Source<>), typeof(Destination<>));
    cfg.CreateMap<DataObject1, DataObject2>();
});

...或者您是否试图避免在编译时知道您可能需要映射DataObject1DataObject2


推荐阅读