使用 AutoMapper 用空值替换空字符串

5 c# automapper

我正在使用 AutoMapper 将 DTO 映射到实体。此外,SAP 正在使用我的 WCF 服务。

问题是 SAP 向我发送空字符串而不是空字符串(即,""而不是null)。

所以我基本上需要遍历我收到的 DTO 的每个字段,并用空值替换空字符串。有没有一种简单的方法可以使用 AutoMapper 完成此操作?

小智 10

考虑映射器配置文件的值转换构造

 CreateMap<Source, Destination>()
.AddTransform<string>(s => string.IsNullOrEmpty(s) ? null : s);
Run Code Online (Sandbox Code Playgroud)

此构造将转换所有“字符串”类型成员,如果它们为 null 或为空,则替换为 null


Sun*_*nov 5

取决于您的追求 - 如果有您想要保留空字符串而不是转换为 null 的字符串字段,或者您想以相同的方式威胁所有这些字段。提供的解决方案是,如果您需要同样威胁他们。如果要指定应发生空到空转换的单个属性,请使用 ForMemeber() 而不是 ForAllMembers。

转换所有解决方案:

namespace Stackoverflow
{
    using AutoMapper;
    using SharpTestsEx;
    using NUnit.Framework;

    [TestFixture]
    public class MapperTest
    {
        public class Dto
        {
            public int Int { get; set; }
            public string StrEmpty { get; set; }
            public string StrNull { get; set; }
            public string StrAny { get; set; }
        }

        public class Model
        {
            public int Int { get; set; }
            public string StrEmpty { get; set; }
            public string StrNull { get; set; }
            public string StrAny { get; set; }
        }

        [Test]
        public void MapWithNulls()
        {
            var dto = new Dto
                {
                    Int = 100,
                    StrNull = null,
                    StrEmpty = string.Empty,
                    StrAny = "any"
                };

            Mapper.CreateMap<Dto, Model>()
                  .ForAllMembers(m => m.Condition(ctx =>
                                                  ctx.SourceType != typeof (string)
                                                  || ctx.SourceValue != string.Empty));

            var model = Mapper.Map<Dto, Model>(dto);

            model.Satisfy(m =>
                          m.Int == dto.Int
                          && m.StrNull == null
                          && m.StrEmpty == null
                          && m.StrAny == dto.StrAny);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


gab*_*bba 5

您可以像这样定义字符串映射:

cfg.CreateMap<string, string>()
    .ConvertUsing(s => string.IsNullOrWhiteSpace(s) ? null : s);
Run Code Online (Sandbox Code Playgroud)