0

We have this web api below and we would like utilise AutoMapper to simplify this code mapping to DTO or vice versa BUT we haven't found the good setup plus how to use this as most of the docs is either utilising .Net Core or and old version of AutoMapper.

The new version of AutoMapper is version 9.

From what I've seen most the mapping are pretty direct BUT in our case we have a CategoryName which is mapped to x.Category.Name etc etc

Can someone point to the right direction here.

Thanks

[HttpGet]
[Route("api/v1/Activities/{sortfields=Id}/{pagenumber=1}/{pagesize=10}")]
[CacheOutput(ClientTimeSpan = 60, ServerTimeSpan = 60)]
public async Task<IHttpActionResult> GetActivities(string sortfields, int pageNumber, int pageSize)
{
    string userId = User.Identity.GetUserId();

    if (!IsOkPropertyValidate(sortfields))
    {
        return BadRequest("Sort property is incorrect");
    }

    var activities = await db.Activities
                             .Include(b => b.User)
                             .Include(c => c.Category)
                             .Where(q => q.UserId == userId).ToListAsync();

    var noOfRecords = activities.Count();

    var activitiesDTO = await (db.Activities
                                 .Include(b => b.User)
                                 .Include(c => c.Category)
                                 .Where(q => q.UserId == userId)
                                 .Select(x => new ActivityDTO
                                    {
                                        Id = x.Id,
                                        OwnerName = x.User.FirstName + " " + x.User.LastName,
                                        CategoryName = x.Category.Name,
                                        Name = x.Name,
                                        Description = x.Description,
                                        NoOfMinutes = x.NoOfMinutes,
                                        DateCreated = x.DateCreated,
                                        DateModified = x.DateModified,
                                    })
                                 .AsQueryable()
                                 .ApplySort(sortfields)
                                 .Skip((pageNumber - 1) * pageSize)
                                 .Take(pageSize)).ToListAsync();    

    var data = new
        {
            Metadata = new {
                            TotalRecords = noOfRecords,
                            CurrentPageSize = pageSize,
                            CurrentPage = pageNumber,
                            TotalPages = (int)Math.Ceiling(noOfRecords / (double)pageSize)
                        },
            Results = activitiesDTO
        };

    return Ok(paginationMetadata);
}
2

1 Answer 1

1

You need to map your property in ModelMappingProfile class

      public class ModelMappingProfile : Profile
      {
        public ModelMappingProfile()
         {
           CreateMap<Category, ActivityDTO>()
            .ForMember(dto => dto.CategoryName , opts =>
            opts.MapFrom(src => src.Category.Name));
         }
       }
Sign up to request clarification or add additional context in comments.

1 Comment

I do something like this instead: private MapperConfiguration configuration = new MapperConfiguration(cfg => cfg.CreateMap<Activity, ActivityDTO>() .ForMember(dto => dto.OwnerName, conf => conf.MapFrom(ol => ol.User.FirstName + " " + ol.User.LastName)) .ForMember(dto => dto.CategoryName, conf => conf.MapFrom(ol => ol.Category.Name)));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.