栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在ASP.NET Core中设置Automapper

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在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世界的新手!



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/421479.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号