My use case is simple. I have a root domain object which references a child object. I have a DTO passed back from a service call that represents the domain object but rather than pass the child object each time, the DTO contains a property that holds the child object's key value. Something like this:
public class DomainObject
{
public ChildObject Child { get; set; }
public String Name { get; set; }
}
public class ChildObject
{
public Int32 Key { get; set; }
public String Name { get; set; }
}
public class DTO
{
public Int32 ChildKey { get; set; }
public String Name { get; set; }
}
I have a cached list开发者_如何转开发 of ChildObjects. When I map from DTO=>DomainObject I want to set the DomainObject.Child property to the existing instance of ChildObject from the cache using the DTO.ChildKey property. Does this require a custom value resolver or is there another way to accomplish this?
Yes you will need a custom value resolver. Something like this will do it:
public class KeyToChildObjectResolver : ValueResolver<Int32, ChildObject>
{
protected override ChildObject ResolveCore(Int32 source)
{
return Cache.Get<ChildObject>(source);
}
}
And then:
Mapper.CreateMap<DTO, DomainObject>()
.ForMember(x => x.Child, o => o.ResolveUsing<KeyToChildObjectResolver>()
.FromMember(x => x.ChildKey));
You could do it with a Resolver that goes straight from DTO to ChildObject but then your resolver is essentially single purpose. This way you can use it anywhere you have a child key to be mapped to a ChildObject
精彩评论