I’m having an issue while using automapper.
following is the relevant code
if (await _appDbContext.PharmaPointEmployees
.Include(nav => nav.BonusRecords)
.FirstOrDefaultAsync(dbEntry =>
dbEntry.EmployeeId == request.EmployeeId &&
dbEntry.PharmaPointId == request.PharmaPointId,
cancellationToken)
is not PharmaPointEmployee pharmaEmployee) return NotFound();
/// at this point pharmaEmployee.BonusRecords contains 1 value
request.MapTo(pharmaEmployee);
/// at this point pharmaEmployee.BonusRecords contains 0 values
where MapTo
public static void MapTo<TDestination>(this object source, TDestination destination)
{
if (_mapper is null) throw new NullReferenceException($"Initialize {nameof(IMapperExtensions._mapper)} at application startup.");
if (source is null) throw new TypeInitializationException(typeof(TDestination).FullName, null);
_mapper.Map(source, destination);
}
mapping profile
public class PutEmployeeBonusRecordRequestProfile : Profile
{
public PutEmployeeBonusRecordRequestProfile()
{
CreateMap<PutEmployeeBonusRecordRequest, PharmaPointEmployee>()
.ForMember(dest => dest.BonusRecords, opt => opt.MapFrom<EmployeePharmaPointsResolver>());
}
private class EmployeePharmaPointsResolver : IValueResolver<PutEmployeeBonusRecordRequest, PharmaPointEmployee, ICollection<BonusRecord>>
{
ICollection<BonusRecord> IValueResolver<PutEmployeeBonusRecordRequest, PharmaPointEmployee, ICollection<BonusRecord>>.Resolve(
PutEmployeeBonusRecordRequest source,
PharmaPointEmployee destination,
ICollection<BonusRecord> destMember,
ResolutionContext context)
{
if (destination.BonusRecords.FirstOrDefault(
item => item.EmployeeId == source.EmployeeId &&
item.PharmaPointId == source.PharmaPointId &&
item.BonusProgramId == source.BonusProgramId &&
item.BranchId == source.BranchId)
is BonusRecord record)
{
record.Agreement.Type = source.BonusType;
record.Agreement.Value = source.BonusValue;
}
else
{
destination.BonusRecords.Add(
new BonusRecord
{
BonusProgramId = source.BonusProgramId,
BranchId = source.BranchId,
EmployeeId = source.EmployeeId,
PharmaPointId = source.PharmaPointId,
Agreement = new BonusRecordAgreement
{
Type = source.BonusType,
Value = source.BonusValue
}
});
}
return destination.BonusRecords;
}
}
}
the pharmaEmployee
value in the caller indicates that it has one record for BonusRecords
, inside the mapper I still can see the value, while also can update the record value. When controll is returned to caller, the pharmaEmployee.BonusRecords
is an empty list. How come ?
locx is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.