[英]AutoMapper: Mapping between DTO and Entity
我正在使用 ASP.NET 核心 WebAPI,我想為我的名為“項目”的對象執行 CRUD。 我正在使用 EF Core 來處理 SQL 數據庫,並且我有兩個代表我的對象的模型。
我的 HTTP GET one 和 HTTP GET many methods 以這樣的方式工作
獲取 ItemRepository 實例
獲取一個或多個ItemEntity
Map 它使用 AutoMapper 到ItemDto這在我的構造函數中初始化,例如
m_itemDtoMapper = new Mapper(new MapperConfiguration(cfg => cfg.CreateMap<ItemEntity, ItemDto>()));
在我的 WebAPI 方法中,我將 map 使用以下行傳遞給 ItemDto(對於 GET 很多情況):
var itemDtos = m_itemDtoMapper.Map<IEnumerable<ItemEntity>, ICollection<ItemDto>>(items);
這很好用,AutoMapper 非常強大。 我現在的問題是:
在您的示例中,您似乎每次都初始化一個新的映射器實例。 我建議您使用 go 以及依賴注入並使用 AutoMapper 映射配置文件。
您可以通過三個簡單的步驟來完成,我認為它可以回答您的兩個問題:
第 1 步:只需創建一個名為 MappingProfile 或類似名稱的新 class :
public class MappingProfile: Profile
{
public MappingProfile()
{
CreateMap<User, AuthenticateDto>(); // One Way
CreateMap<User, UserDto>().ReverseMap(); // Reverse
}
}
第 2 步:在 Startup.cs 中注冊 Automapper
// Register AutoMapper
services.AddAutoMapper(Assembly.GetExecutingAssembly());
第 3 步:通過 DI 使用您的映射器
public UserService(IMapper mapper) {
_mapper = mapper;
}
// call it as you already did
_mapper.Map<User, UserDto>(user);
希望它可以幫助你:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.