Automapper标志枚举

时间:2016-10-14 11:59:57

标签: c# enums automapper

我正在写一个mvc网站,它通过viewmodels获取一些信息。 这是我的db poco

public class ServiceTime : BaseEntity
{
    public int IdRestaurant { get; set; }
    public virtual Restaurant Restaurant { get; set; }
    public  Src.OrderStar.Entities.Day Day { get; set; }
    public string StartTime { get; set; }
    public string FinishTime { get; set; }
}

这是我的视图模型

public class ServiceTimeModel
{
    public int Id { get; set; }
    public int IdRestaurant { get; set; }
    public bool Monday { get; set; }
    public bool Tuesday { get; set; }
    public bool Wednesday { get; set; }
    public bool Thursday { get; set; }
    public bool Friday { get; set; }
    public bool Saturday { get; set; }
    public bool Sunday { get; set; }
    public DateTime StartTime { get; set; }
    public DateTime FinishTime { get; set; }
}

我正在通过automapper将这些类转换为彼此。我可以通过此配置轻松地将ServiceTime转换为ServiceTimeModel

cfg.CreateMap<ServiceTime, ServiceTimeModel>()
            .ForMember(dest => dest.Monday, opt => opt.MapFrom(src => src.Day.HasFlag(Day.Monday)))
            .ForMember(dest => dest.Tuesday, opt => opt.MapFrom(src => src.Day.HasFlag(Day.Tuesday)))
            .ForMember(dest => dest.Wednesday, opt => opt.MapFrom(src => src.Day.HasFlag(Day.Wednesday)))
            .ForMember(dest => dest.Thursday, opt => opt.MapFrom(src => src.Day.HasFlag(Day.Thursday)))
            .ForMember(dest => dest.Friday, opt => opt.MapFrom(src => src.Day.HasFlag(Day.Friday)))
            .ForMember(dest => dest.Saturday, opt => opt.MapFrom(src => src.Day.HasFlag(Day.Saturday)))
            .ForMember(dest => dest.Sunday, opt => opt.MapFrom(src => src.Day.HasFlag(Day.Sunday)))
            .IgnoreAllNonExisting();

我不能与此相反,我的意思是无法解决如何将ServiceTimeModel绑定到ServiceTime

我想绑定五个不同日期来标记枚举

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

使用 ResolveUsing 方法并创建自己的实现。 例如:(它不好,但有效)

cfg.CreateMap<ProductServiceTimeModel, ProductServiceTime>()
    .ForMember(dest => dest.Day, opt => opt.ResolveUsing(src => 
    {
       Src.OrderStar.Entities.Day result = (src.Monday ? Day.Monday : 0) | (src.Tuesday ? Day.Tuesday: 0) | (src.Wednesday ? Day.Wednesday : 0) | (src.Thursday ? Day.Thursday: 0) | (src.Friday ? Day.Friday : 0) | (src.Saturday ? Day.Saturday : 0) | (src.Sunday ? Day.Sunday: 0);
       return result;
    }));