ASP.NET CORE 3.1 WebApi 引用AutoMapper

本文介绍了如何在C#项目中使用AutoMapper库进行实体与视图实体之间的映射配置。首先,通过NuGet添加了AutoMapper和其依赖注入扩展包。接着,创建了`Demo`实体和`DemoViewModel`视图实体,并定义了它们之间的映射关系。然后,自定义了`CustomProfile`配置类和`AutoMapperConfig`静态类来注册映射。最后,在服务层中展示了如何利用DI容器获取`IMapper`实例并进行映射操作。

一、添加引用包

  <PackageReference Include="AutoMapper" Version="10.1.1" />
  <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="8.1.1" />

二、创建实体和视图实体

public class DemoViewModel
{
    public string DemoName { get; set; }
}
public class Demo
{
    public int Id { get; set; }
    public string Name { get; set; }
}

三、映射关系配置

public class CustomProfile:Profile
{
    /// <summary>
    /// 配置构造函数,用来创建关系映射
    /// </summary>
    public CustomProfile()
    {
        CreateMap<Demo, DemoViewModel>().ForMember(d=>d.DemoName,o=>o.MapFrom(s=>s.Name));
        CreateMap<DemoViewModel, Demo>().ForMember(d=>d.Name,o=>o.MapFrom(s=>s.DemoName));
    }
}
public static class AutoMapperSetup
{
     public static void AddAutoMapperSetup(this IServiceCollection services)
     {
         if (services == null) throw new ArgumentNullException(nameof(services));

         services.AddAutoMapper(typeof(AutoMapperConfig));
         AutoMapperConfig.RegisterMappings();
     }
 }
public class AutoMapperConfig
{
     public static MapperConfiguration RegisterMappings()
     {
         return new MapperConfiguration(cfg =>
         {
             cfg.AddProfile(new CustomProfile());
         });
     }
 }
 #region AutoMapper
 services.AddAutoMapperSetup();
 #endregion

四、使用,在Serv层调用IMapper

public class DemoServ : IDemoServ
{
    private readonly IDemoRepo _demoRepo;
    private readonly IMapper _mapper;

    public DemoServ(IDemoRepo demoRepo,IMapper mapper)
    {
        _demoRepo = demoRepo;
        _mapper = mapper;
    }

    public DemoViewModel GetDemos()
    {
        return _mapper.Map<DemoViewModel>(_demoRepo.GetDemos());
    }
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值