CSharp · Console
using System;
using System.IO;
using AutoMapper;
using System.Collections.Generic;
namespace Example
{
public class OrderLine
{
}
public class OrderLineDTO
{
}
public class DescriptionAttribute : Attribute
{
private readonly string _description;
public DescriptionAttribute(string description)
{
_description = description;
}
public string Description
{
get
{
return _description;
}
}
}
public enum OrderStatus
{
[Description("Paid")]
Paid,
[Description("Processing")]
InProcess,
[Description("Delivered")]
Sent
}
public static class ExtensionMethods
{
static public string GetDescription(this OrderStatus This)
{
var type = typeof(OrderStatus);
var memInfo = type.GetMember(This.ToString());
var attributes = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
return ((DescriptionAttribute)attributes[0]).Description;
}
}
public class Order {
public int Id { get; set; }
public List<OrderLine> OrderLines { get; set; }
public OrderStatus Status { get; set; }
}
public class OrderDTO {
public int Id { get; set; }
public List<OrderLineDTO> OrderLines { get; set; }
public string Status { get; set; }
}
public class Program
{
static public void Main()
{
Mapper.Initialize
(
cfg =>
{
cfg.CreateMap<Order, OrderDTO>()
.ForMember
(
dest => dest.Status,
opt => opt.MapFrom
(
src => src.Status.GetDescription()
)
);
}
);
var o = new Order();
o.Status = OrderStatus.Sent;
var dto = Mapper.Map<OrderDTO>(o);
Console.WriteLine(dto.Status);
}
}
}