.Net Core中使用 AutoMapper

1、添加引用

install-package AutoMapper

install-package AutoMapper.Extensions.Microsoft.DependencyInjection

2、配置

2.1創建配置文件

 public class AutoMapperConfig : Profile
    {
        public AutoMapperConfig()
        {
            CreateMap<UserEntity, UserViewModel>();
            CreateMap<UserDTO, UserEntity>();
        }
    }

2.2註冊

public void ConfigureServices(IServiceCollection services)
        {
//新增代碼
            services.AddAutoMapper(typeof(AutoMapperConfig));
        }

3、使用

 private readonly IMapper _mapper;
        public UsersController(SQLDbContext dbContext, IMapper mapper)
        {
            _mapper = mapper;
        }

/// <summary>
        /// 新增用戶
        /// </summary>
        /// <param name="userDTO"></param>
        /// <returns></returns>
        [Route("Add")]
        [HttpPost]
        public bool Add(UserDTO userDTO)
        {
            var entity = _mapper.Map<UserEntity>(userDTO);
            _dbContext.Set<UserEntity>().Add(entity);
            return _dbContext.SaveChanges() > 0;
        }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章