小编典典

如何在ASP.NET Core中设置Automapper

c#

我是.NET的新手,所以我决定使用.NET Core,而不是学习“旧方法”。我在这里找到了有关为.NET
Core设置AutoMapper
的详细文章,但是对于新手来说,是否有更简单的演练?


阅读 775

收藏
2020-05-19

共1个答案

小编典典

我想到了!详细信息如下:

  1. 通过NuGet将主要的AutoMapper软件包添加到您的解决方案中。
  2. 通过NuGet将AutoMapper依赖项注入程序包添加到您的解决方案中。

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

    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 mappingConfig = new MapperConfiguration(mc =>
    {
    mc.AddProfile(new MappingProfile());
    });

    IMapper mapper = mappingConfig.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!
    }
    

    }

我希望这可以帮助某人从ASP.NET Core重新开始!我欢迎任何反馈或批评,因为我还是.NET世界的新手!

2020-05-19