空值替换

NullSubstitute 空替换

如果成员链任意位置上的源值为 null,空替换(NullSubstitute)可以为目标成员提供备用值。
它并不是直接从 null 完成映射,而是使用你提供的备用值来进行映射。

简单理解:源属性为 null,就使用配置的默认替换值;源属性不为 null,则直接使用源本身的值。

using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            var config = new MapperConfiguration(cfg => cfg.CreateMap<Source, Destination>()
                .ForMember(destination => destination.Value2, opt => opt.NullSubstitute("Other Value")));
            var mapper = config.CreateMapper();

            var source = new Source { Value2 = null };
            var dest = mapper.Map<Source, Destination>(source);

            source.Value2 = "Not null";

            dest = mapper.Map<Source, Destination>(source);

            Console.ReadKey();
        }
    }

    public class Source
    {
        public string Value2 { get; set; }
    }

    public class Destination
    {
        public string Value2 { get; set; }
    }
}Code language: JavaScript (javascript)

运行结果说明:

  1. source.Value2 = nulldest.Value2 = "Other Value"(触发空替换)
  2. source.Value2 = "Not null"dest.Value2 = "Not null"(源不为null,直接取源的值)

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注