I have an ASP.Net core 6 mvc project that's divided over 3 Layers (UI, Logic, Data). All 3 layers have different model-classes. So I created a folder in UI and Logic called Mappings
, both have a mapping-profile class.
After adding builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
to my Program.cs
, my app complains about Missing type map configuration or unsupported mapping.
public class MappingProfile : Profile
{
// UI-Layer
public MappingProfile()
{
CreateMap<TraderViewModel, TraderDTO>().ReverseMap();
CreateMap<TaskViewModel, TaskDTO>().ReverseMap();
CreateMap<TaskRewardViewModel, TaskRewardDTO>().ReverseMap();
CreateMap<OwnedItemViewModel, OwnedItemDTO>().ReverseMap();
CreateMap<ItemViewModel, ItemDTO>().ReverseMap();
}
}
public class MappingProfileBusiness : Profile
{
// Business-Layer
public MappingProfileBusiness()
{
CreateMap<Trader, TraderDTO>().ReverseMap();
CreateMap<Task, TaskDTO>().ReverseMap();
CreateMap<TaskReward, TaskRewardDTO>().ReverseMap();
CreateMap<OwnedItem, OwnedItemDTO>().ReverseMap();
CreateMap<Item, ItemDTO>().ReverseMap();
}
}
public List<TraderDTO> GetAllTraders()
{
List<TraderDTO> traderDtos = new List<TraderDTO>();
List<Trader> traders = _DAL.GetAllTraders();
foreach (Trader trader in traders)
{
// IMapper mapper;
// Error being thrown here
traderDtos.Add(mapper.Map<TraderDTO>(trader));
}
return traderDtos;
}
CodePudding user response:
You should add the Mapper Profiles to Program.cs.
by automatically scanning for profiles
var config = new MapperConfiguration(cfg => { cfg.AddMaps(myAssembly); }); var configuration = new MapperConfiguration(cfg => cfg.AddMaps(myAssembly))
or manually
var config = new MapperConfiguration(cfg => { cfg.AddProfile<OrganizationProfile>(); cfg.AddProfile(new OrganizationProfile()); }
Source : https://docs.automapper.org/en/stable/Configuration.html#profile-instances
when using mapper, Assign the object in the constructor for dependency injection
ex:
public class Class1
{
public Class1(IMapper mapper)
{
Mapper = mapper;
}
public IMapper Mapper { get; }
public DestModel GetData()
{
Mapper.Map<DestModel>(SourceModel);
}
}
CodePudding user response:
All I had to change was in my Program.cs
builder.Services.AddAutoMapper(typeof(MappingProfile), typeof(MappingProfileBusiness));
I added the mappingprofiles in the AddAutoMapper()
.