3

I have the following classes:

public class Entity
{
      public string Name { get; set; }
}       
public class SomethingDto
{
     public string NameChanged { get; set; }
     public void Mapping(Entity something)
     {
         NameChanged = something.Name;
     }          
}

I want to use the Mapping Method of the DTO to create the map as the following way:

conf.CreateMap<Entity, SomethingDto>().ForMember(t => t.NameChanged, opt => opt.MapFrom(t => t.Name));

There is a way in AutoMapper to create the maps with custom methods, who works with his projection?

1
  • You can have a constructor instead. The docs. Commented Aug 27, 2017 at 4:56

1 Answer 1

8

You don't want to do it like that, because that makes the DTO aware of the entity and that would throw out the separation you'd get.

Now in this case, the line ForMember(t => t.NameChanged, opt => opt.MapFrom(t => t.Name)) will work because Name and NameChanged are both of type string. Say you'd like to do something along the lines of mapping identifier of type string with value '20180120-00123456' to two properties on the destination: a DateTime property and a ProductId property. You can do this two ways.

Simple

You would write two mapping functions in the class where you make the mapping and do it along the lines of:

  • ForMember(t => t.Date, opt => opt.MapFrom(t => RetrieveDate(t.Identifier)))
  • ForMember(t => t.ProductId, opt => opt.MapFrom(t => RetrieveProductId(t.Identifier)))

Complex

You would make a custom class OrderIdentifier (now I'm assuming the identifier is for an order) with only the Id property as string. Then you'd make two custom type converters, like the article describes.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.