Replacing empty strings with nulls with AutoMapper

我们两清 提交于 2020-05-15 03:38:53

问题


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

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

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?


回答1:


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.

Convert all solution:

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);
        }
    }
}



回答2:


Consider value transform construction for mapper profile

 CreateMap<Source, Destination>()
.AddTransform<string>(s => string.IsNullOrEmpty(s) ? null : s);

This construction will transform all 'string' type members and if they null or empty replace with null




回答3:


You can just define string mapping like this:

cfg.CreateMap<string, string>()
    .ConvertUsing(s => string.IsNullOrWhiteSpace(s) ? null : s);


来源:https://stackoverflow.com/questions/16591682/replacing-empty-strings-with-nulls-with-automapper

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!