gpt4 book ai didi

c# - 如何在 ASP.NET Core 中设置 Automapper

转载 作者:IT王子 更新时间:2023-10-29 03:29:46 27 4
gpt4 key购买 nike

我是 .NET 的新手,因此我决定着手解决 .NET Core 而不是学习“旧方法”。我找到了一篇关于 setting up AutoMapper for .NET Core here 的详细文章,但是对于新手有更简单的演练吗?

最佳答案

我想通了!详情如下:

  1. 通过 NuGet 将主要的 AutoMapper 包添加到您的解决方案中.

  2. 通过 NuGet 将 AutoMapper 依赖注入(inject)包添加到您的解决方案中.

  3. 为映射配置文件创建一个新类。 (我在名为 MappingProfile.cs 的主解决方案目录中创建了一个类,并添加了以下代码。)我将使用 UserUserDto对象为例。

     public class MappingProfile : Profile {
    public MappingProfile() {
    // Add as many of these lines as you need to map your objects
    CreateMap<User, UserDto>();
    CreateMap<UserDto, User>();
    }
    }
  4. 然后在Startup.cs中添加AutoMapperConfiguration,如下所示:

     public void ConfigureServices(IServiceCollection services) {
    // .... Ignore code before this

    // Auto Mapper Configurations
    var mapperConfig = new MapperConfiguration(mc =>
    {
    mc.AddProfile(new MappingProfile());
    });

    IMapper mapper = mapperConfig.CreateMapper();
    services.AddSingleton(mapper);

    services.AddMvc();

    }
  5. 要在代码中调用映射对象,请执行如下操作:

     public class UserController : Controller {

    // Create a field to store the mapper object
    private readonly IMapper _mapper;

    // Assign the object in the constructor for dependency injection
    public UserController(IMapper mapper) {
    _mapper = mapper;
    }

    public async Task<IActionResult> Edit(string id) {

    // Instantiate source object
    // (Get it from the database or whatever your code calls for)
    var user = await _context.Users
    .SingleOrDefaultAsync(u => u.Id == id);

    // Instantiate the mapped data transfer object
    // using the mapper you stored in the private field.
    // The type of the source object is the first type argument
    // and the type of the destination is the second.
    // Pass the source object you just instantiated above
    // as the argument to the _mapper.Map<>() method.
    var model = _mapper.Map<UserDto>(user);

    // .... Do whatever you want after that!
    }
    }

关于c# - 如何在 ASP.NET Core 中设置 Automapper,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40275195/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com