简体   繁体   English

Automapper 以及泛型和映射缺失的属性

[英]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:所以我以这种方式设置了 Automapper,它来自文档:

        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.值 ---> AutoMapper.AutoMapperConfigurationException:找到未映射的成员。 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:如果你映射你的映射会成功DataObject1DataObject2当您配置映射器,像这样:

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? ...或者您是否试图避免在编译时知道您可能需要将DataObject1映射到DataObject2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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