How to create a map to enumerate in iqueryable mapping in auto mapper?

class Program
    {
        static void Main(string[] args)
        {
            var emp1 = new Soure.Employee();
            emp1.TestEnum = Soure.MyEnum1.red;
            var emp2 = new Soure.Employee();
            emp2.TestEnum = Soure.MyEnum1.yellow;
            var empList = new List<Soure.Employee>() { emp1, emp2 }.AsQueryable();
            var mapExpr = Mapper.CreateMap<Soure.Employee, destination.Employee>();
            Mapper.CreateMap<Soure.Department, destination.Department>();
            Mapper.CreateMap<Soure.MyEnum1, destination.MyEnum2>();
            Mapper.AssertConfigurationIsValid();
            var mappedEmp = empList.Project().To<destination.Employee>();

        }  
    }

      

I am mapping Source.Employee to Destination.Employee. All properties can be matched. But when displaying an enum, it gives me an exception, unable to map TestEnum to Int32 If I use override

var mapExpr = Mapper.CreateMap<Soure.Employee, destination.Employee>()
        .ForMember(x => x.TestEnum, opt => opt.MapFrom(s => (destination.MyEnum2)s.TestEnum));

      

Then it works.

The mapping classes are shown below:

namespace Soure
{
    public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }

        public Department dept { get; set; }

        public int age { get; set; }

        public MyEnum1 TestEnum { get; set; }

        public Employee()
        {
            this.Id = 1;
            this.Name = "Test Employee  Name";
            this.age = 10;
            this.dept = new Department();
        }
    }

    public class Department
    {
        public int Id { get; set; }
        public string DeptName { get; set; }

        Employee emp { get; set; }

        public Department()
        {
            Id = 2;
            DeptName = "Test Dept";
        }
    }

    public enum MyEnum1
    {
        red,
        yellow
    }
}

namespace destination
{
    public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }

        public int age { get; set; }
        public MyEnum2 TestEnum { get; set; }

        public Department dept { get; set; }

    }

    public class Department
    {
        public int Id { get; set; }
        public string DeptName { get; set; }

        Employee emp { get; set; }
    }
    public enum MyEnum2
    {
        red,
        yellow
    }
}

      

+3


source to share


1 answer


Below are two ways to map counters using AutoMapper ...

.ForMember(x => x.TestEnum, opt => opt.MapFrom(s => (int)s.TestEnum));

      



Another approach would be to use ConstructUsing

mapper.CreateMap<TestEnum, Soure.MyEnum1>().ConstructUsing(dto => Enumeration.FromValue<Soure.MyEnum1>((int)dto.MyEnum2));

      

+1


source







All Articles