AutoMapper 基本使用 Mapster

1、Initialize:Mapper 初始化

Mapper.Initialize(x =>
    x.CreateMap<Destination, Source>()
);

Mapper.Initialize(cfg =>
{
    cfg.CreateMap<Aliens, Person>();
});

Mapper.Initialize(cfg => {
    cfg.CreateMap<Foo, FooDto>();
    cfg.CreateMap<Bar, BarDto>();
});

2、映射前、映射后 操作

Mapper.Initialize(x =>
    x.CreateMap<Destination, Source>()
    .BeforeMap((src, dest) => src.InfoUrl = "https://" + src.InfoUrl)
    .AfterMap((src, dest) => src.name = "真棒" + src.name));

cfg.CreateMap<ClassBannerDo, ClassBannerDto>()
    .BeforeMap((source, dto) =>
    {
        if (!string.IsNullOrEmpty(source.ImgUrl))
            source.ImgUrl = StringPlus.GetWebConfigKey("ImageDomain") + source.ImgUrl;
        if (!string.IsNullOrEmpty(source.Thumbnail))
            source.Thumbnail = StringPlus.GetWebConfigKey("ImageDomain") + source.Thumbnail;
    });

cfg.CreateMap<StudentInoutDo, StudentInoutDto>()
    // f.字符串 f => 枚举描述
    .ForMember(f => f.InOutDisplay, f => f.MapFrom(m => m.Inout == 1 ? EnumInout.In.GetEnumDescription() : EnumInout.Out.GetEnumDescription()));
    // f.枚举 f => 枚举
    .ForMember(f => f.InOutEnum, f => f.MapFrom(m => m.Inout == 1 ? EnumInout.In : EnumInout.Out))
    // 实体对象序列化 json 字符串
    .ForMember(f => f.School, f => f.MapFrom(m => JsonConvert.SerializeObject(m.School)))
    .ReverseMap()
    // 数据库中为 json 字符串,反序列化 实体对象
    .ForMember(f => f.School, f => f.MapFrom(m => JsonConvert.DeserializeObject<SchoolDo>(m.School)));

public enum EnumInout
{
    Normal = 0,
    [Description("进校")]
    In = 1,
    [Description("出校")]
    Out = 2
}

3、条件映射

Mapper.Initialize(x => 
    x.CreateMap<Destination, Source>()
    .ForMember(dest => dest.InfoUrl, opt => opt.Condition(dest => dest.InfoUrl == "www.cnblogs.com/zaranet1"))
    .ForMember(...(.ForMember(...))));

4、多类映射

public static void Configure()
{
    Mapper.Initialize(cfg =>
    {
        cfg.AddProfile<DestinationSourceProfile>();
        cfg.AddProfile(new StudentSourceProfile());
    });
}

5、CreateMap【配置 AutoMapper】 与 Mapper.Map【执行映射,执行 mapping】

Mapper.CreateMap<Order, OrderDto>();
OrderDto dto = Mapper.Map<Order, OrderDto>(order);
var fooDto = Mapper.Map<FooDto>(foo);
var barDto = Mapper.Map<BarDto>(bar);

6、忽略字段,隐藏字段

Mapper.CreateMap<Source, Destination>()
    .ForMember(dest => dest.SomeValuefff, opt => opt.Ignore());

==============.NET Core AutoMapper==============

1、Nuget安装

AutoMapper       
AutoMapper.Extensions.Microsoft.DependencyInjection  //需要依赖注入AutoMapper,需要下载该包。

2、在Startup中添加AutoMapper

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    // 添加对AutoMapper的支持
    services.AddAutoMapper(typeof(WebMapperInit));

    #region 添加对AutoMapper的支持,添加 IConfiguration 依赖注入
    services.AddSingleton(provider => new MapperConfiguration(cfg =>
    {
        cfg.AddProfile(new WebMapperInit(provider.GetService<IConfiguration>()));
    }).CreateMapper());
    #endregion

}

3、创建AutoMapper映射配置文件

using AutoMapper;
using Hospital.Entity;
using Hospital.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Hospital.WebAPI
{
    public class WebMapperInit : Profile
    {
        #region 添加 IConfiguration 依赖注入
        private IConfiguration _configuration;

        public WebMapperInit(IConfiguration configuration)
        {
            _configuration = configuration;

            CreateMap<base_patient, PatientRequest>()
                .ForMember(d => d.Id, option => option.MapFrom(s => s.id))
                .ForMember(d => d.UserId, option => option.MapFrom(s => s.user_id))
                .ForMember(d => d.HospitalId, option => option.MapFrom(s => s.hospital_id))
                .ForMember(d => d.CreatedTime, option => option.MapFrom(s => s.created_time))
                .ForMember(d => d.ModifyTime, option => option.MapFrom(s => s.modify_time))
                .ForMember(d => d.Status, option => option.MapFrom(s => s.status))
                .ReverseMap();
        }
        #endregion

        public WebMapperInit()
        {
            CreateMap<base_patient, PatientRequest>()
                .ForMember(d => d.Id, option => option.MapFrom(s => s.id))
                .ForMember(d => d.UserId, option => option.MapFrom(s => s.user_id))
                .ForMember(d => d.HospitalId, option => option.MapFrom(s => s.hospital_id))
                .ForMember(d => d.CreatedTime, option => option.MapFrom(s => s.created_time))
                .ForMember(d => d.ModifyTime, option => option.MapFrom(s => s.modify_time))
                .ForMember(d => d.Status, option => option.MapFrom(s => s.status))
                .ReverseMap();
        }
    }
}

4、Controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Hospital.Entity;
using Hospital.Models;
using Hospital.Repository;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Hospital.WebAPI.Controllers
{
    [Route("")]
    [ApiController]
    public class PatientController : ControllerBase
    {
        private readonly IPatientRepository _patientRepo;
        private readonly IMapper _mapper;

        public PatientController(IMapper mapper, IPatientRepository patientRepo)
        {
            _patientRepo = patientRepo;
            _mapper = mapper;
        }

        [HttpPost]
        public CreatePatientResponse C([FromBody]PatientRequest request)
        {
            request.HospitalId = Guid.NewGuid();
            _patientRepo.AddWithGuid(_mapper.Map<base_patient>(request));

            return new CreatePatientResponse();
        }
    }
}

5、静态文件

--
var config = new MapperConfiguration(cfg => cfg.CreateMap<E, T>());
var mapper = config.CreateMapper();
mapper.Map<T>

--
public UserRepository(AssetDbContext context) : base(context)
{
  var config = new MapperConfiguration(cfg => cfg.CreateMap<UserDto, UserDo>());
  var mapper = config.CreateMapper();
}

6、
*、


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

KingCruel

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值