在 .NET Web API(非核心)上使用 AutoMapper

Using AutoMapper on .NET Web API (not Core)

我们在下面有这个网站 api,我们想利用 AutoMapper 来简化此代码到 DTO 的映射,反之亦然,但我们还没有找到好的设置以及如何使用它作为大多数文档正在使用 .Net Core 或旧版本的 AutoMapper。

AutoMapper 的新版本是版本 9。

据我所知,大多数映射都非常直接,但在我们的例子中,我们有一个映射到 x.Category.Name 等的 CategoryName 等

谁能指出正确的方向。

谢谢

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

您需要在 ModelMappingProfile class

中映射您的 属性
      public class ModelMappingProfile : Profile
      {
        public ModelMappingProfile()
         {
           CreateMap<Category, ActivityDTO>()
            .ForMember(dto => dto.CategoryName , opts =>
            opts.MapFrom(src => src.Category.Name));
         }
       }