簡體   English   中英

Web Api in.Net Core中如何使用AutoMapper?

[英]How to use AutoMapper in Web Api in .Net Core?

目前,我有這個 Web Api 方法手動將我的實體 map 我的實體到 DTO ZA8CFDE6311.C49EB2AC96F 沒有問題 Now, I would like to implement AutoMapper which I have installed in registered in in ConfigureServices method and created the AutoMapper profile class and injected automapper in my Web Api controller constructor.

這是我沒有 AutoMapper 的手動映射

[HttpGet]
    public async Task<ActionResult<IEnumerable<MovieDto>>> GetMovies()
    {
        //manual mapping which can be replaced with Automapper
        var movies = (from m in _context.Movies
                      select new MovieDto()
                      {
                          Id = m.Id,
                          MovieTitle = m.MovieTitle,
                          ReleaseDate = m.ReleaseDate,
                          MovieStatus = m.MovieStatus,
                          PhotoFile = m.PhotoFile
                      }).ToListAsync();

        return await movies;

    }

這就是我嘗試添加自動映射器以替換手動映射的方式。

[HttpGet]
public async Task<ActionResult<IEnumerable<MovieDto>>> GetMovies()
{
      return _mapper.Map<IEnumerable<MovieDto>>(_context.Movies);
}

但是,它遇到錯誤Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<CinemaApp.NETCore31.WebAPI.Models.MovieDto>' to 'Microsoft.AspNetCore.Mvc.ActionResult<System.Collections.Generic.IEnumerable<CinemaApp.NETCore31.WebAPI.Models.MovieDto>>'

您將需要創建一個配置文件和 map 所有您想做的轉換。 您不必逐個字段進行此操作,只要名稱相同,就可以讓 AutoMapper 弄清楚。

這似乎是一個很好的教程: https://code-maze.com/automapper-net-core/

首先在 AutoMapper 中創建一個繼承自 Profile class 的 class

public class MappingProfile : Profile 
{
   public MappingProfile()
   {
      CreateMap<Movie, MovieDto>();
   }
}

請注意,如果您想從MovieDtoMovie的 map ,則必須創建第二條CreateMap線。

在您的Startup.cs class 中,您需要注冊 Automapper,這將自動掃描程序集中使用此代碼定義 Startup class 的所有配置文件:

public void ConfigureServices(IServiceCollection services)
{
   services.AddAutoMapper(typeof(Startup));
}

如果您使用的是AutoMapper V9 ,您可以像這樣使用ProjectTo擴展方法

private readonly IMapper _mapper;

public MovieController(IMapper mapper)
{
    _mapper = mapper;
}

[HttpGet]
public async Task<ActionResult<IEnumerable<MovieDto>>> GetMovies()
{
      return await _context.Movies
                .ProjectTo<MovieDto>(_mapper.ConfigurationProvider)
                .ToListAsync();
}

要使用ProjectTo ,您需要添加AutoMapper.QueryableExtensions命名空間。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM