简体   繁体   中英

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

Your mapping will succeed if you map DataObject1 to DataObject2 when you configure your mapper like so:

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

... or are you trying to avoid having to know at compile time that you may need to map DataObject1 to DataObject2 at all?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM