如何在ASP.NET Core中设置Automapper

如何在ASP.NET Core中设置Automapper,第1张

如何在ASP.NET Core中设置Automapper

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

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

  3. 映射配置文件创建一个新类。(我在主解决方案目录中创建了一个名为的类,

    MappingProfile.cs
    并添加了以下代码。)我将使用
    User
    and
    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 pre 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 objectprivate readonly IMapper _mapper;// Assign the object in the constructor for dependency injectionpublic UserController(IMapper mapper) {    _mapper = mapper;}public async Task<IActionResult> Edit(string id) {    // Instantiate source object    // (Get it from the database or whatever your pre 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世界的新手!



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5064173.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-16
下一篇 2022-11-16

发表评论

登录后才能评论

评论列表(0条)

保存