[英]AutoMapper: Mapping between DTO and Entity
I am working with a ASP.NET Core WebAPI and I want to do CRUD for my objects called "Item".我正在使用 ASP.NET 核心 WebAPI,我想为我的名为“项目”的对象执行 CRUD。 I am using EF Core to work with a SQL Database and I have two models that represents my objects.
我正在使用 EF Core 来处理 SQL 数据库,并且我有两个代表我的对象的模型。
My HTTP GET one and HTTP GET many methods works in such way that it我的 HTTP GET one 和 HTTP GET many methods 以这样的方式工作
Get ItemRepository instance获取 ItemRepository 实例
Fetch one or more ItemEntity获取一个或多个ItemEntity
Map it to ItemDto by using AutoMapper This is initalized in my constructor such as Map 它使用 AutoMapper 到ItemDto这在我的构造函数中初始化,例如
m_itemDtoMapper = new Mapper(new MapperConfiguration(cfg => cfg.CreateMap<ItemEntity, ItemDto>()));
And in my WebAPI method I map it to a ItemDto with the following line (for the GET many case):在我的 WebAPI 方法中,我将 map 使用以下行传递给 ItemDto(对于 GET 很多情况):
var itemDtos = m_itemDtoMapper.Map<IEnumerable<ItemEntity>, ICollection<ItemDto>>(items);
This works well and the AutoMapper is very powerful.这很好用,AutoMapper 非常强大。 The questions I have now is:
我现在的问题是:
In your example, it seems that you initialize each time a new mapper instance.在您的示例中,您似乎每次都初始化一个新的映射器实例。 I would suggest you go along with dependency injection and make use of AutoMapper Mapping Profiles.
我建议您使用 go 以及依赖注入并使用 AutoMapper 映射配置文件。
You can do it in three simple steps and I think it answers both of your questions:您可以通过三个简单的步骤来完成,我认为它可以回答您的两个问题:
Step 1: Simply create a new class called MappingProfile or something similar:第 1 步:只需创建一个名为 MappingProfile 或类似名称的新 class :
public class MappingProfile: Profile
{
public MappingProfile()
{
CreateMap<User, AuthenticateDto>(); // One Way
CreateMap<User, UserDto>().ReverseMap(); // Reverse
}
}
Step 2: Register Automapper in Startup.cs第 2 步:在 Startup.cs 中注册 Automapper
// Register AutoMapper
services.AddAutoMapper(Assembly.GetExecutingAssembly());
Step 3: Consume your mapper over DI第 3 步:通过 DI 使用您的映射器
public UserService(IMapper mapper) {
_mapper = mapper;
}
// call it as you already did
_mapper.Map<User, UserDto>(user);
Hopefully it helps you:)希望它可以帮助你:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.