32

Could someone please explain how I can use Automapper to map from DB int value to a string, using Enums as the collection.

I have the following

Enum

public enum Status { Open, Closed }

EF 4.1 Domain Model

public class MyEntity
{
    ...
    public int StatusId { get; set; }
    public virtual Status Status { get; set; }    
}

Dto being used on website

public class MyEntityDto
{
    public string Status { get; set; }
}

Current Automapper mappings

Mapper.CreateMap<int, Status>().ConvertUsing<EnumConverter<Status>>();
Mapper.CreateMap<Enum, string>().ConvertUsing(src => src.ToString());

Mapper.CreateMap<MyEntity, MyEntityDto>()
                .ForMember(d => d.Status, o => o.MapFrom(y => y.StatusId))

The EnumConverter in first line converts the int to a status fine without problem, but how do i convert the int or Status to the string in the DTO? Im lost any help would be appreciated.

I realise there are 2 conversions required here, the id to the enum when the data is pulled from the database and enum needs populating and then the enum to string needs doing

Cheers

2 Answers 2

65
Mapper.CreateMap<MyEntity, MyEntityDto>()
      .ForMember(destination => destination.Status, 
                 opt => opt.MapFrom(source => Enum.GetName(typeof(Status), source.StatusId)));

Also you don't need mapping from int to Status enum.

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

2 Comments

Awesome Thanks for your help, so simple in the end :)
Also may this thread be usefull so : stackoverflow.com/questions/9721466/…
0

In case you need int to enum conversion, you can use explicit cast:

Mapper.CreateMap<MyEntity, MyEntityDto>()
      .ForMember(destination => destination.Status, 
                 opt => opt.MapFrom(source => (Status)source.StatusId));

The cast (Status) tells the compiler to interpret the value integer value from source.StatusId as a value of the Status enum.

1 Comment

Both your case and the initial case are default conversions, you don't need ForMember.

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.