dcpartners
dcpartners

Reputation: 5446

Using AutoMapper on .NET Web API (not Core)

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);
}

Upvotes: 0

Views: 224

Answers (1)

awais
awais

Reputation: 515

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));
         }
       }

Upvotes: 1

Related Questions