当前位置: 首页 > 工具软件 > AutoMapper > 使用案例 >

automapper

杨研
2023-12-01

AutoMapper在模型映射过程中起着重要的作用,首先添加两个包引用
nuget automapper
nuget AutoMapper.Extensions.Microsoft.DependencyInjection
创建模型类与它所对应的Dto

public class User
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public string Phone { get; set; }
        public string Fax { get; set; }
        public DateTime DateOfBirth { get; set; }
    }
    public class UserDto
    {
        public long Id { get; set; }
        public string FullName { get; set; }
        public DateTime DateOfBirth { get; set; }
    }

配置映射文件

public MappingProfile()
        {
            CreateMap<User, UserDto>()
                .ForMember(dest=>dest.FullName,o=>o.MapFrom(src=>src.Name));
        }

在startup.cs中注册服务

var mappingConfig = new MapperConfiguration(mc =>
            {
                mc.AddProfile(new MappingProfile());
            });
            IMapper mapper = mappingConfig.CreateMapper();
            services.AddSingleton(mapper);

在controller的action中生成映射对象

var user = new User { Id = 10, Name = "yong hu", Phone = "" };
            var model = _mapper.Map<UserDto>(user);
            return Json(model);
 类似资料: