无法弄清楚如何在 RESTful API 中使用带有后期操作的自动映射器



我有一个简单的RESTful API,这是我试图在中应用AutoMapper的路由后处理程序

[HttpPost]
[Route("[action]")]
public async Task<IActionResult> CreateHotel([FromBody]Hotel hotelCreateDto)
{
var hotel = _mapper.Map<Hotel>(hotelCreateDto);
var createdHotel = await _hotelService.CreateHotel(hotel);
var hotelReadDto = _mapper.Map<HotelReadDto>(createdHotel);
return CreatedAtAction("GetHotelById", new { id = hotelReadDto.Id }, hotelReadDto);
}

所以在请求中,我得到了一个看起来像这样的hotelCreateDto:

public class HotelCreateDto
{
[StringLength(50)]
[Required]
public string Name { get; set; }
[StringLength(50)]
[Required]
public string City { get; set; }
}

我将其映射到酒店实体:

public class Hotel
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[StringLength(50)]
[Required]
public string Name { get; set; }
[StringLength(50)]
[Required]
public string City { get; set; }
}

并且在下一行中创建新的酒店对象。然而,当hotelReadDto将被分配给新映射的对象时,出现500错误:自动映射器。AutoMapperMappingException:缺少类型映射配置或不受支持的映射";

你能在这里发现一个错误吗?我不知道我哪里做错了。

编辑:在上面的错误之后还有这样的东西:"映射类型:对象->HotelReadDto系统对象->HotelFinder。DTO。DTO。HotelReadDto";

编辑2:这是配置服务中的代码:

services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

在Profile类中:

public class HotelProfile : Profile
{
public HotelProfile()
{
CreateMap<Hotel, HotelReadDto>();
CreateMap<HotelCreateDto, Hotel>();
}
}

在启动时将其添加到您的服务中:

它是可重复使用且更清洁的

public void ConfigureServices(IServiceCollection services)
{
services.AddAutoMapper(Assembly.GetExecutingAssembly());
}

在项目中添加这些接口和类

public interface IMapFrom<T>
{
void Mapping(Profile profile) => profile.CreateMap(typeof(T), GetType());
}
using AutoMapper;
using System;
using System.Linq;
using System.Reflection;
public class MappingProfile : Profile
{
public MappingProfile()
{
ApplyMappingsFromAssembly(Assembly.GetExecutingAssembly());
}
private void ApplyMappingsFromAssembly(Assembly assembly)
{
var types = assembly.GetExportedTypes()
.Where(t => t.GetInterfaces()
.Any(i =>i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IMapFrom<>)))
.ToList();
foreach (var type in types)
{
var instance = Activator.CreateInstance(type);
var methodInfo = type.GetMethod("Mapping")
?? type.GetInterface("IMapFrom`1").GetMethod("Mapping");
methodInfo?.Invoke(instance, new object[] { this });
}
}
}

你的dto是这样的(将酒店映射到HotelDto(:

public class HotelCreateDto : IMapFrom<HotelCreateDto>
{
[StringLength(50)]
[Required]
public string Name { get; set; }
[StringLength(50)]
[Required]
public string City { get; set; }
public void Mapping(Profile profile)
{
profile.CreateMap<Hotel,HotelCreateDto>();
}
}

最新更新