如何在自动映射器中的可查询映射中为枚举创建映射
本文关键字:映射 查询 创建 枚举 | 更新日期: 2023-09-27 18:36:58
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>();
}
}
我正在将Source.Employee映射到Destination.Employee。可以映射所有属性。但是在枚举映射上,它给了我异常,无法将TestEnum映射到Int32如果我使用覆盖
var mapExpr = Mapper.CreateMap<Soure.Employee, destination.Employee>()
.ForMember(x => x.TestEnum, opt => opt.MapFrom(s => (destination.MyEnum2)s.TestEnum));
然后它起作用了。
映射类如下面所示
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
}
}
以下是使用自动映射器映射枚举器的 2 种方法...
.ForMember(x => x.TestEnum, opt => opt.MapFrom(s => (int)s.TestEnum));
另一种方法是使用 ConstructUsing
mapper.CreateMap<TestEnum, Soure.MyEnum1>().ConstructUsing(dto => Enumeration.FromValue<Soure.MyEnum1>((int)dto.MyEnum2));