Automapper在.net核心的反向映射中不起作用

问题描述 投票:0回答:3

我正在将.Net core与Entity Framework一起使用。下面是我的代码

查看模型

public class EmployeeVm
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string ContactNo { get; set; }
        public string Email { get; set; }
        public DateTime JoiningDate { get; set; }
        public int BranchId { get; set; }
        public int DepartmentId { get; set; }
    }

POCO类别

public class employee
    {
        [Key]
        public int id { get; set; } 
        public string name { get; set; }
        public string contact_no { get; set; }
        public string email { get; set; }
        public DateTime joining_date { get; set; }
        public int branch_id { get; set; }
        public int department_id { get; set; }      
    }

启动类中的Automapper配置

public void ConfigureServices(IServiceCollection services)
        {
            var mappingConfig = new MapperConfiguration(mc =>
            {
                mc.AddProfile(new MappingProfile());
            });

            IMapper mapper = mappingConfig.CreateMapper();
            services.AddSingleton(mapper);
        }

映射配置文件类

public class MappingProfile : Profile
    {
        public MappingProfile()
        {
            CreateMap<employee, EmployeeVm>();
            CreateMap<EmployeeVm, employee>();
        }
    }

当我尝试使用下面的代码将View Model属性映射到POCO类属性时,它工作正常。

//Here I am using constructor injection
private readonly IMapper _mapper;
public EmployeeBl(IMapper mapper)
{
    _mapper = mapper;
}

_mapper.Map<employee>(employeeVm)

但是当我尝试将POCO类(employee)属性映射到视图模块(EmployeeVm)属性时,某些属性未映射,因为它包含POCO类中的下划线

这是邮递员的回复

{
    "id": 4,
    "name": "test",
    "contactNo": null,
    "email": "[email protected]",
    "joiningDate": "0001-01-01T00:00:00",
    "branchId": 0,
    "departmentId": 0,
}

从上述响应中,我希望将contactNo,joiningDate,branchId和departmentId属性映射为各自的值。

c# automapper asp.net-core-webapi
3个回答
0
投票

您还可以在配置中映射具有差异名称的道具

Mapper.CreateMap<employee, EmployeeVm>()
    .ForMember(dest => dest.JoiningDate, opt => opt.MapFrom(src => joining_date ));

0
投票

https://docs.automapper.org/en/stable/Configuration.html#naming-conventions

您可以设置源和目标命名约定

var configuration = new MapperConfiguration(cfg => {
  cfg.SourceMemberNamingConvention = new LowerUnderscoreNamingConvention();
  cfg.DestinationMemberNamingConvention = new PascalCaseNamingConvention();
});

这将相互映射以下属性:property_name-> PropertyName

您也可以在每个配置文件级别设置此>]

public class OrganizationProfile : Profile
{
  public OrganizationProfile()
  {
    SourceMemberNamingConvention = new LowerUnderscoreNamingConvention();
    DestinationMemberNamingConvention = new PascalCaseNamingConvention();
    //Put your CreateMap... Etc.. here
  }
}

0
投票

AutoMapper不会自动将snake_case映射到PascalCase。您必须按照此处所述配置命名约定:https://docs.automapper.org/en/v9.0.0/Configuration.html#naming-conventions

© www.soinside.com 2019 - 2024. All rights reserved.