I have an Asp.Net web API project. And I'm implementing a shopping cart. So I have models that have to be converted to Dtos. So I'm using automapper to map Models
to Dtos so I can transfer data but for some reason, I'm getting the following error.
The error message I get:
"Error mapping types.\r\n\r\nMapping types:\r\nCartModel -> CartDto\r\nMoby.Services.ShoppingCart.API.Models.CartModel -> Moby.Services.ShoppingCart.API.Models.Dto.CartDto\r\n\r\nType Map configuration:\r\nCartModel -> CartDto\r\nMoby.Services.ShoppingCart.API.Models.CartModel -> Moby.Services.ShoppingCart.API.Models.Dto.CartDto\r\n\r\nDestination Member:\r\nCartDetails\r\n"
Automapper config class:
public class MapperConfig
{
public static MapperConfiguration RegisterMaps()
{
return new MapperConfiguration(config =>
{
config.CreateMap<CartModel, CartDto>().ReverseMap();
config.CreateMap<CartHeaderModel, CartHeaderDto>().ReverseMap();
config.CreateMap<CartDetailsModel, CartDetailsDto>().ReverseMap();
config.CreateMap<ProductModel, ProductDto>().ReverseMap();
});
}
}
Automapper dependency injection:
var mapper = MapperConfig.RegisterMaps().CreateMapper();
builder.Services.AddSingleton(mapper);
builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
CartModel:
public class CartModel
{
public CartHeaderModel CartHeader { get; set; }
public IEnumerable<CartDetailsModel> CartDetails { get; set; }
}
CartDto:
public class CartDto
{
public CartHeaderDto CartHeader { get; set; }
public IEnumerable<CartDetailsDto> CartDetails { get; set; }
}
CartDetailsModel:
public int Id { get; set; }
public int CartHeaderId { get; set; }
[ForeignKey(nameof(CartHeaderId))]
public virtual CartHeaderModel CartHeader { get; set; }
public int ProductId { get; set; }
[ForeignKey(nameof(ProductId))]
public virtual ProductModel Product { get; set; }
public int Count { get; set; }
CartDetailsDto
public class CartDetailsDto
{
public int Id { get; set; }
public int CartHeaderId { get; set; }
public virtual CartHeaderDto CartHeader { get; set; }
public int ProductId { get; set; }
public virtual ProductModel Product { get; set; }
public int Count { get; set; }
}
CodePudding user response:
Define your mapping inside a class that extends Profile
class.
public class MappingProfile : Profile
{
public MappingProfile()
{
CreateMap<CartModel, CartDto>().ReverseMap();
CreateMap<CartHeaderModel, CartHeaderDto>().ReverseMap();
CreateMap<CartDetailsModel, CartDetailsDto>().ReverseMap();
CreateMap<ProductModel, ProductDto>().ReverseMap();
}
}
Remove these lines:
var mapper = MapperConfig.RegisterMaps().CreateMapper();
builder.Services.AddSingleton(mapper);
Only keep this line:
builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
AddAutoMapper
will scan the assemblies for any classes that extend Profile
and load the mapping configuration from them. I will also register a mapper that you can inject in your services (IMapper
).