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
Convert int to Enum using Enum.Use the Enum. ToObject() method to convert integers to enum members, as shown below.
The built-in enum mapper is not configurable, it can only be replaced. Alternatively, AutoMapper supports convention based mapping of enum values in a separate package AutoMapper.
We can convert an enum to string by calling the ToString() method of an Enum.
There are two ways to convert an Enum to String in Java, first by using the name() method of Enum which is an implicit method and available to all Enum, and second by using toString() method.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With