2016-08-16 11 views
2

Automapperを使用して、nullコレクションのクラスを同じコレクションの宛先にマップします。宛先コレクションもnullにする必要があります。Automapper:プロファイルでAllowNullCollectionsを設定する

ProfileクラスにはAllowNullCollectionsというプロパティがあります。マッピングには影響しません。 cfg.AllowNullCollectionsをTrueに設定すると、マッピングによって宛先コレクションが(必要な場合)nullのままになります。

システムのすべてのマッピングでAllowNullCollectionsをTrueに設定できません。プロファイルにのみ適用する必要があります。

using System.Collections.Generic; 
using AutoMapper; 
using NUnit.Framework; 
using Assert = NUnit.Framework.Assert; 


namespace Radfords.FreshCool.Web.Tests 
{ 
    [TestFixture] 
    [Category("UnitTest")] 
    class AutomapperTests 
    { 
     private IMapper _mapper; 

     // this says that AllowNullCollections does work at the profile level, in May. 
     //https://github.com/AutoMapper/AutoMapper/issues/1264 

     [SetUp] 
     public void SetUp() 
     { 

      var config = new MapperConfiguration(cfg => 
      { 
       cfg.AddProfile<TestMappingProfile>(); 
       // I want the profile to set the configuration, if I set this here the test passes 
       //cfg.AllowNullCollections = true; 
      }); 
      _mapper = config.CreateMapper(); 
     } 


     [Test] 
     [Category("UnitTest")] 
     public void MapCollectionsTest_MustBeNull() 
     { 
      var actual = _mapper.Map<Destination>(new Source()); 

      Assert.IsNull(actual.Ints, "Ints must be null."); 
     } 

    } 

    internal class TestMappingProfile : Profile 
    { 
     public TestMappingProfile() 
     { 
      AllowNullCollections = true; 

      CreateMap<Source, Destination>(); 
     } 
    } 

    internal class Source 
    { 
     public IEnumerable<int> Ints { get; set; } 
    } 

    internal class Destination 
    { 
     public IEnumerable<int> Ints { get; set; } 
    } 
} 
+0

これはバグだと思います。私は[レポに問題を提出しました](https://github.com/AutoMapper/AutoMapper/issues/1618)より詳しい情報を入手してください –

+0

しかし、追加するべきことは次のとおりです。 "私はAllowNullCollectionsを設定できません私のシステムのすべてのマッピングでTrueにするには、私のプロファイルにのみ適用する必要があります。これが意図です。プロファイルはグローバル設定を変更せず、マップするタイプの設定のみを変更します。 –

+0

ご返信ありがとうございます。明確にするにはグローバルに適用されるため、allownullcollectionsをtrueに設定することはできません。プロファイルレベルでallownullcollectionsをtrueに設定する必要があります。 – WilliamsC

答えて

0

レイはgithubに関する問題を提出しましたか?現在の状態では、利益レベルでAllowNullCollectionsを設定できないため、設定レベルでそれを設定する必要があります。

0

あなたは以下でTestMappingProfile CTORを置き換えることができ、それが動作するはずです:。

公共TestMappingProfile() {

CreateMap()ForMember(DEST => dest.Ints、OPT =>オプト.Condition(src =>(src.Ints!= null)));
}

+0

提案していただきありがとうございます。私がマッピングしているクラスには多くのコレクションがあり、メンバーレベルでのマッピングを指定するのは理想的ではありません。 – WilliamsC

関連する問題