使用AutoMapper将空字符串替换为null [英] Replacing empty strings with nulls with AutoMapper

查看:362
本文介绍了使用AutoMapper将空字符串替换为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using AutoMapper to map DTOs to entities. Also, my WCF services are being consumed by SAP.

问题是SAP向我发送了空字符串而不是空值(即""而不是null).

The issue is that SAP sends me empty strings instead of nulls (that is, "" instead of null).

因此,我基本上需要遍历接收到的DTO的每个字段,并将空字符串替换为null.有没有简便的方法可以通过AutoMapper完成此操作?

So I basically need to go through every field of the DTO I am receiving, and replace empty strings by nulls. Is there an easy way to accomplish this with AutoMapper?

推荐答案

取决于您要执行的操作-如果存在要保留其空字符串而不转换为null的字符串字段,或者您要威胁他们都是一样的.提供的解决方案是如果您需要同样地威胁它们.如果要指定应进行空到空转换的单个属性,请使用ForMemeber()而不是ForAllMembers.

Depends on what you are after - if there are string fields for which you would like to preserve the empty string and not convert to null, or you want to threat all of them the same. The provided solution is if you need to threat them all the same. If you want to specify individual properties for which the empty to null conversion should happen, use ForMemeber() instead of 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);
        }
    }
}

这篇关于使用AutoMapper将空字符串替换为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆