.Net Core 中使用AutoMapper
2024-10-20 16:48:26
1、新建一个类
using AutoMapper;
using YourModels;
using YourViewModels;
namespace YourNamespace
{
public class AutoMapperProfileConfiguration : Profile
{
protected override void Configure()
{
CreateMap<Application, ApplicationViewModel>();
CreateMap<ApplicationViewModel, Application>();
...
}
}
}
2、在Startup.cs中增加MapperConfiguration属性
private MapperConfiguration _mapperConfiguration { get; set; }
3、在Startup.cs中的Startup方法中增加
_mapperConfiguration = new MapperConfiguration(cfg =>
{
cfg.AddProfile(new AutoMapperProfileConfiguration());
});
4、在ConfigureServices()中增加
services.AddSingleton<IMapper>(sp => _mapperConfiguration.CreateMapper());
5、使用
using AutoMapper;
using ...
namespace YourNamespace
{
public class ApplicationsController : BaseController
{
[FromServices]
private IMapper _mapper { get; set; }
[FromServices]
private IApplicationRepository _applicationRepository { get; set; }
public ApplicationsController(
IMapper mapper,
IApplicationRepository applicationRepository)
{
_mapper = mapper;
_applicationRepository = applicationRepository;
}
// GET: Applications
public async Task<IActionResult> Index()
{
IEnumerable<Application> applications = await _applicationRepository.GetForIdAsync(...);
if (applications == null)
return HttpNotFound();
List<ApplicationViewModel> viewModel = _mapper.Map<List<ApplicationViewModel>>(applications);
return View(viewModel);
}
...
}
最新文章
- C语言计算字符串子串出现的次数
- iis6403、 iis7403.14
- [ActionScript 3.0] AS3.0 对象在一定范围随机显示不重叠
- Java内部类this$0字段产生的一个bug
- 寻找子串位置 codevs 1204
- 【Android开发经验】来,咱们自己写一个Android的IOC框架!
- web端和手机端测试有什么不同
- ios中点语法、property跟synthesize用法
- vmware克隆虚拟机后进行网络配置
- quartz任务调度框架与spring整合
- Rsync服务实战
- txt2xls
- Codeforces Round #410 (Div. 2) B
- Beta阶段冲刺三
- Java中的yield关键字的简单讲解
- 1050. [HAOI2006]旅行【并查集+枚举】
- html5在手机熄屏后倒计时会出现延迟情况
- 福利来了,全国路网数据,poi数据
- ZOJ 3706 Break Standard Weight 解题报告
- Windows平台上的pip安装