从字典到字段的自动映射器

问题描述 投票:0回答:2
using System;
using AutoMapper;
using System.Linq;
using System.Collections.Generic;

namespace AutoMapperDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Address empAddres = new Address()
            {
                City = "Mumbai",
                State = "Maharashtra",
                Country = "India"
            };
            Employee emp = new Employee();
          
            emp.Department = "IT";
            emp.address = empAddres;

            var mapper =InitializeAutomapper();
            var empDTO = mapper.Map<EmployeeDTO>(emp);

            Console.WriteLine("Output :" + empDTO.JsonExtensionData["Department"]);
            Console.ReadLine();
        }
        
        static Mapper InitializeAutomapper()
        {

            var config = new MapperConfiguration(cfg => {
                cfg.CreateMap<Employee, EmployeeDTO>()
                    .ForMember(src => (src.JsonExtensionData.First(p => p.Key == "Department").Value), act => act.MapFrom(dest => dest.Department))
                     .ForMember(src => (src.JsonExtensionData.First(p => p.Key == "Address").Value), act => act.MapFrom(dest => dest.address));                
            });
            
            var mapper = new Mapper(config);
            return mapper;
        }
    }

    public class Employee
    {
        public string Department { get; set; }
        public Address address { get; set; }
    }
    public class EmployeeDTO
    {
       public Dictionary<string, object> JsonExtensionData { get; set; }
    }

    public class Address
    {
        public string City { get; set; }
        public string State { get; set; }
        public string Country { get; set; }
    }
}

链接:https://dotnetfiddle.net/jvoTo6 出现异常=>

未处理的异常。 AutoMapper.AutoMapperMappingException:缺少类型映射配置或不支持的映射。

映射类型: 对象 -> EmployeeDTO System.Object -> AutoMapperDemo.EmployeeDTO 在 lambda_method1(闭包,对象,EmployeeDTO,ResolutionContext) 在 AutoMapperDemo.Program.Main(String[] args) 命令由信号 6 终止

  1. 我该如何纠正?
  2. 如果我尝试直接使用 .reverseMapping 进行反向映射,那么反向映射会起作用吗?
c# automapper
2个回答
0
投票

您可以使用

IValueResolver
在源和目标之间映射不同的字段类型


    using System;
    using AutoMapper;
    using System.Collections.Generic;
    
    namespace AutoMapperDemo {
    class Program {
      static void Main(string[] args) {
        Employee emp = new Employee();
    
        emp.Department = "IT";
    
        var mapper = InitializeAutomapper();
        var empDTO = mapper.Map<EmployeeDTO>(emp);
    
        Console.WriteLine("Output :" + empDTO.JsonExtensionData["Department"]);
    
        EmployeeDTO empDTO2 = new EmployeeDTO();
    
        empDTO2.JsonExtensionData["Department"] = "HR";
        var newEmp = mapper.Map<Employee>(empDTO2);
    
        Console.WriteLine("Output :" + newEmp.Department);
      }
    
      static Mapper InitializeAutomapper() {
        var config = new MapperConfiguration(cfg => {
          cfg.CreateMap<Employee, EmployeeDTO>()
              .ForMember(dest => dest.JsonExtensionData,
                         opt => opt.MapFrom<ObjToDictResolver>())
              .ReverseMap()
              .ForMember(dest => dest.JsonExtensionData,
                         opt => opt.MapFrom<ObjToDictMapper>());
        });
    
        var mapper = new Mapper(config);
        return mapper;
      }
    }
    
    public class ObjToDictResolver
        : IValueResolver<object, object, Dictionary<string, object>> {
      public Dictionary<string, object> Resolve(
          object source, object dest, Dictionary<string, object> destMember,
          ResolutionContext context) {
        var result = new Dictionary<string, object>();
        result["Department"] = ((Employee) source).Department;
        return result;
      }
    }
    
    public class DictToObjectResolver : IValueResolver<object, object, string> {
      public string Resolve(object source, object dest, string destMember,
                            ResolutionContext context) {
        return ((string)(((EmployeeDTO) source).JsonExtensionData)["Department"]);
      }
    }
    
    public class Employee {
      public string Department {
        get;
        set;
      }
    }
    
    public class EmployeeDTO {
      public Dictionary<string, object> JsonExtensionData {
        get;
        set;
      } = new Dictonary<string, object>();
    }
    }


0
投票

要使用自动映射器,源对象和目标对象的属性必须具有相同的名称。

您可以使用此代码:

public class EmployeeDTO
{
    public string Department { get; set; }
    public Address address { get; set; }
}

并类似地使用它:

Console.WriteLine("Output :" + JsonConvert.SerializeObject(emp.address));
© www.soinside.com 2019 - 2024. All rights reserved.