简体   繁体   中英

C#: How can I make automapper map a property of type object?

This is the source object:

public class Source {
    public object Obj { get; set; }
}

Here object is actually a SourcePropertyType .

I want to convert Source to this:

public class Destination {
    public object Obj { get; set; }
}

where object is DestinationPropertyType (which is identical to SourcePropertyType )

var destination = map.Map<Source, Destination>(source);
var myObj = destination.Obj as DestinationPropertyType;

In the above code myObj == null even if Obj on the source is set.

I hope this makes sense. How can I change the AutoMapper configuration so that it understands that the destination is a DestinationPropertyType and maps it as it would normally?

By "identical to SourcePropertyType " I am assuming you mean that they have the same properties and types. In that case, you just need to have AutoMapper make a map between the two and configure the map for the containing type to use it:

Mapper.CreateMap<SourcePropertyType, DestinationPropertyType>();
Mapper.CreateMap<Source, Destination>()
      .ForMember(d => d.obj,
                 o => o.MapFrom(s => Mapper.Map<DestinationPropertyType>(s.obj As SourcePropertyType) as Object);

Note that if the property types were the actual types instead of object you wouldn't need the extra configuration.

Unbox the objects to specific types before you run it through Automapper. Automapper will not be able to map an object to an object.

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