zoukankan      html  css  js  c++  java
  • 映射验证

    Hand-rolled mapping code, though tedious, has the advantage of being testable. One of the inspirations behind AutoMapper was to eliminate not just the custom mapping code, but eliminate the need for manual testing. Because the mapping from source to destination is convention-based, you will still need to test your configuration.

    AutoMapper provides configuration testing in the form of the AssertConfigurationIsValid method. Suppose we have slightly misconfigured our source and destination types:

        public class Source
        {
        	public int SomeValue { get; set; }
        }
        
        public class Destination
        {
        	public int SomeValuefff { get; set; }
        }
    

    In the Destination type, we probably fat-fingered the destination property. Other typical issues are source member renames. To test our configuration, we simply create a unit test that sets up the configuration and executes the AssertConfigurationIsValid method:

        Mapper.Initialize(cfg => 
          cfg.CreateMap<Source, Destination>());
        
        Mapper.Configuration.AssertConfigurationIsValid();
    

    Executing this code produces an AutoMapperConfigurationException, with a descriptive message. AutoMapper checks to make sure that every single Destination type member has a corresponding type member on the source type.

    Overriding configuration errors

    To fix a configuration error (besides renaming the source/destination members), you have three choices for providing an alternate configuration:

    • Custom value resolver
    • [[Projection]]
    • Use the Ignore() option

    With the third option, we have a member on the destination type that we will fill with alternative means, and not through the Map operation.

        Mapper.Initialize(cfg => 
          cfg.CreateMap<Source, Destination>()
        	.ForMember(dest => dest.SomeValuefff, opt => opt.Ignore())
        );
    

    Selecting members to validate

    By default, AutoMapper uses the destination type to validate members. It assumes that all destination members need to be mapped. To modify this behavior, use the CreateMap overload to specify which member list to validate against:

        Mapper.Initialize(cfg => 
          cfg.CreateMap<Source, Destination>(MemberList.Source);
          cfg.CreateMap<Source2, Destination2>(MemberList.None);
        );
    

    To skip validation altogether for this map, use MemberList.None. This is the default when calling ReverseMap().

  • 相关阅读:
    [自娱自乐] 4、超声波测距模块DIY笔记(四)——终结篇·基于C#上位机软件开发
    [新概念51单片机C语言教程·郭天祥] 1、 基础知识必备
    [起重机监测系统] 2、国标、架构及待测数据方案
    [自娱自乐] 3、超声波测距模块DIY笔记(三)
    [起重机监测系统] 1、基于无线传输的桥式起重机的安全监测方案
    [OpenCV] 3、直线提取 houghlines
    关于MySQL的行转列的简单应用
    java 模拟发送post请求测试
    拦截器通过Spring获取工厂类,注入bean对象
    springboot 表单校验
  • 原文地址:https://www.cnblogs.com/Leman/p/5774025.html
Copyright © 2011-2022 走看看