AutoMapper Enum to byte with implemention IMapperConfigurator

前端 未结 3 702
温柔的废话
温柔的废话 2021-02-07 11:44

Enum definition is

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

public class RowStatusEnumConvertor : IMapperConfigurator
{
           


        
3条回答
  •  我在风中等你
    2021-02-07 12:21

    Starting from version 9 of Automapper there were changes in initialization which caused to be out of date above examples. I updated above example and left original values to have also reference to older version (NUnit 3.12.0):

    RowStatusEnum

    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
        {
            public MyProfile()
            {
                CreateMap().ConvertUsing(
                    x => Enum.GetValues(typeof(RowStatusEnum))
                        .Cast().First(y => (byte)y == x));
                CreateMap().ConvertUsing(
                    x => (byte)x);
            }
        }
    }
    

    MappingTests

    namespace StackOverflow.RowStatus
    {
        using AutoMapper;
    
        using NUnit.Framework;
    
        [TestFixture]
        public class MappingTests
        {
            [Test]
            public void AutoMapper_Configuration_IsValid()
            {
                var config = new MapperConfiguration(cfg => cfg.AddProfile());
                config.AssertConfigurationIsValid();
            }
    
            [TestCase(1, ExpectedResult = RowStatusEnum.Modified)]
            [TestCase(2, ExpectedResult = RowStatusEnum.Removed)]
            [TestCase(3, ExpectedResult = RowStatusEnum.Added)]
            public RowStatusEnum AutoMapper_ConvertFromByte_IsValid(
                byte rowStatusEnum)
            {
                var config = new MapperConfiguration(cfg => cfg.AddProfile());
                var mapper = config.CreateMapper();
                return mapper.Map(rowStatusEnum);
            }
    
            [TestCase(RowStatusEnum.Modified, ExpectedResult = 1)]
            [TestCase(RowStatusEnum.Removed, ExpectedResult = 2)]
            [TestCase(RowStatusEnum.Added, ExpectedResult = 3)]
            public byte AutoMapper_ConvertFromEnum_IsValid(
                RowStatusEnum rowStatusEnum)
            {
                var config = new MapperConfiguration(cfg => cfg.AddProfile());
                var mapper = config.CreateMapper();
                return mapper.Map(rowStatusEnum);
            }
        }
    }
    

提交回复
热议问题