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.”
                            缺少类型映射配置或不支持的映射
  • 相关阅读:
    java.lang.NoClassDefFoundError: org/apache/commons/fileupload/disk/DiskFileItemFactory
    连续子数组的最大和
    @Scheduled(cron = "* * * * * *")
    BigDecimal加减乘除计算
    04
    作业03
    作业01
    Haar小波的理解
    Matlab画colormap的一种色彩搭配方法
    单自由度系统中质量、阻尼和刚度变化对频率响应函数(FRF)影响图的绘制
  • 原文地址:https://www.cnblogs.com/mi21/p/12212874.html
Copyright © 2011-2022 走看看