zoukankan      html  css  js  c++  java
  • AutoMapper集成

    包管理器添加

    AutoMapper
    
    AutoMapper.Extensions.Microsoft.DependencyInjection

    创建AutoMapper文件夹,在文件夹中创建AutoMapperConfig.cs类(也可以不创建文件夹,重要是为了代码简洁,方便观看)

    /// <summary>
        /// 静态全局 AutoMapper 配置文件
        /// </summary>
        public class AutoMapperConfig
        {
            public static MapperConfiguration RegisterMappings()
            {
                return new MapperConfiguration(cfg =>
                {
                    cfg.AddProfile(new CustomProfile());
                });
            }
        }

    上面 CustomProfile 还没有创建

    按AIt+Enter在新文件中生成CustomProfile或者在AutoMapper 文件夹中创建CustomProfile,继承Profile

      public class CustomProfile : Profile
        {
            /// <summary>
            /// 配置构造函数,用来创建关系映射
            /// </summary>
            public CustomProfile()
            {
                //第一个参数是原对象,第二个是目的对象
                CreateMap<Person, PersonViewModel>();
            }
        }

    Person和PersonViewModel 下面有

    使用 在Controller中 依赖注入

            private readonly IMapper _mapper;
            public WeatherForecastController( IMapper mapper)
            {
                _mapper = mapper;
            }

    用于演示的两个类

    一般在开发中AutoMapper使用的场景都是实体类和ViewModel的转换

    public class Person
        {
            public Guid Id { get; set; }
            public string Name { get; set; }
            public string height { get; set; }
            public string wieght { get; set; }
            public string Education { get; set; }
        }
     public class PersonViewModel
        {
            public Guid Id { get; set; }
            public string Name { get; set; }
            public string Education { get; set; }
        }

    使用

      Person person = new Person()
                {
                    Id = Guid.NewGuid(),
                    Name="张翼德",
                    height="八尺",
                    wieght="五百斤",
                    Education="文盲"
                };
      PersonViewModel model = _mapper.Map<PersonViewModel>(person);

    一定要在CustomProfile类中配置,否侧会报错

    AutoMapper.AutoMapperMappingException:“Missing type map configuration or unsupported mapping.”
                            缺少类型映射配置或不支持的映射
  • 相关阅读:
    phpStudy mysql升级至5.7
    apache 子域名自动与子域名同名的目录绑定
    js 移动端获取当前用户的经纬度
    PHPStudy环境下搭建composer
    MySQL sock 文件丢失被删除解决方法
    Nginx+Php-fpm运行原理详解
    服务器反爬虫攻略:Apache/Nginx/PHP禁止某些User Agent抓取网站
    php 下载文件/直接下载数据内容
    window 克隆复制当前窗口
    staff
  • 原文地址:https://www.cnblogs.com/mi21/p/12212874.html
Copyright © 2011-2022 走看看