AutoMapper Enum to byte with implemention IMapperConfigurator

前端 未结 3 1479
一生所求
一生所求 2021-02-07 11:25

Enum definition is

public enum RowStatusEnum
{
    Modified = 1,
    Removed = 2,
    Added = 3
}

public class RowStatusEnumConvertor : IMapperConfigurator
{
           


        
3条回答
  •  旧巷少年郎
    2021-02-07 12:00

    Will something like this work for you?

    Classes.cs

    namespace StackOverflow.RowStatus
    {
        public enum RowStatusEnum
        {
            Modified = 1,
            Removed = 2,
            Added = 3
        }
    }
    

    AutoMapperConfigurator.cs

    namespace StackOverflow.RowStatus
    {
        using System;
        using System.Linq;
    
        using AutoMapper;
    
        public class MyProfile : Profile
        {
            protected override void Configure()
            {
                Mapper.CreateMap().ConvertUsing(
                    x => Enum.GetValues(typeof(RowStatusEnum))
                             .Cast().First(y => (byte)y == x));
                Mapper.CreateMap().ConvertUsing(
                    x => (byte)x);
            }
        }
    }
    

    MappingTests.cs

    namespace StackOverflow.RowStatus
    {
        using AutoMapper;
    
        using NUnit.Framework;
    
        [TestFixture]
        public class MappingTests
        {
            [Test]
            public void AutoMapper_Configuration_IsValid()
            {
                Mapper.Initialize(m => m.AddProfile());
                Mapper.AssertConfigurationIsValid();
            }
    
            [TestCase(1, Result = RowStatusEnum.Modified)]
            [TestCase(2, Result = RowStatusEnum.Removed)]
            [TestCase(3, Result = RowStatusEnum.Added)]
            public RowStatusEnum AutoMapper_ConvertFromByte_IsValid(
                                                       byte rowStatusEnum)
            {
                Mapper.Initialize(m => m.AddProfile());
                Mapper.AssertConfigurationIsValid();
                return Mapper.Map(rowStatusEnum);
            }
    
            [TestCase(RowStatusEnum.Modified, Result = 1)]
            [TestCase(RowStatusEnum.Removed, Result = 2)]
            [TestCase(RowStatusEnum.Added, Result = 3)]
            public byte AutoMapper_ConvertFromEnum_IsValid(
                                                       RowStatusEnum rowStatusEnum)
            {
                Mapper.Initialize(m => m.AddProfile());
                Mapper.AssertConfigurationIsValid();
                return Mapper.Map(rowStatusEnum);
            }
        }
    }
    

提交回复
热议问题