2013-05-16 2 views
1

AutoMapper를 사용하여 DTO를 엔티티에 매핑합니다. 또한 SAP에서 내 WCF 서비스를 사용하고 있습니다.빈 문자열을 AutoMapper로 null로 바꾸기

문제는 SAP가 NULL 대신 null 문자열 (즉, null 대신 "")을 보냅니다.

그래서 기본적으로 수신 할 DTO의 모든 필드를 살펴보고 빈 문자열을 null로 대체해야합니다. AutoMapper로이 작업을 쉽게 수행 할 수 있습니까?

+0

을 사용하면 시스템의 모든 개체에 대해이 작업을 수행 하시겠습니까? – Maciej

+0

예, 시스템의 모든 객체에 필요합니다. 감사! –

답변

1

빈 문자열을 보존하고 null로 변환하지 않으려는 문자열 필드가 있거나 그 모두를 동일하게 위협하려는 문자열 필드가있는 경우에 따라 다릅니다. 제공된 솔루션은 위협을 모두 가할 필요가있는 경우입니다. 빈에서 null로 변환 할 개별 속성을 지정하려면 ForAllMembers 대신 ForMemeber()를 사용하십시오.

변환 모든 솔루션 :

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

감사합니다. 매우 감사. –

관련 문제