0

ジェネリック コレクションを含むクラスをマップしようとしていますが、そのクラスを別のカスタム タイプのコレクションである別のクラスにマップしたいと考えています。ただし、マッピングを実行しようとすると、AutomapperMapperException が発生します。問題を再現する簡単なテスト プロジェクトを作成しました。

[TestFixture]
public class Test
{
    [Test]
    public void TestBehavior()
    {
        Mapper.CreateMap<TestEntity, TestDto>()
              .ForMember(x => x.Foos, m => m.ResolveUsing<FooCollectionResolver>());

              //.ForMember(x => x.Foos, m => m.Ignore())
              //.AfterMap((testEntity, testDto) =>
              //{ testDto.Foos = new FooCollection<Foo>(testEntity.Foos); });

        Mapper.AssertConfigurationIsValid();

        var entity = new TestEntity()
        {
            Id = Guid.NewGuid(),
            Name = "Test entity",
            Foos = new Collection<Foo>
            {
                new Foo { Id = Guid.NewGuid(), Name = "First" },
                new Foo { Id = Guid.NewGuid(), Name = "Second "},
                new Foo { Id = Guid.NewGuid(), Name = "Third" }
            }
        };

        var dto = Mapper.Map<TestDto>(entity);

        Assert.IsNotNull(dto);
    }
}

public class FooCollectionResolver : ValueResolver<TestEntity, IFooCollection<Foo>>
{
    protected override IFooCollection<Foo> ResolveCore(TestEntity source)
    {
        return new FooCollection<Foo>(source.Foos) {CustomProperty = "Something interesting"};
    }
}

// Custom collection class looks like this (simplified for this example)
public class FooCollection<T> : IFooCollection<T>
{
    public FooCollection(IEnumerable<T> items)
    {
        Items = items;
    }

    protected IEnumerable<T> Items { get; set; }

    public IEnumerator<T> GetEnumerator()
    {
        return Items.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    public string CustomProperty { get; set; }
}

Mapper.Map() メソッドを呼び出すと、次の例外が発生します。これは、FooCollection から IFooCollection にマップする方法がわからないことを示唆しています。

Mapping types:
FooCollection`1 -> IFooCollection`1
AutomapperTest.FooCollection`1[[AutomapperTest.Foo, AutomapperTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] -> AutomapperTest.IFooCollection`1[[AutomapperTest.Foo, AutomapperTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]

Destination path:
TestDto.Foos.Foos

Source value:
AutomapperTest.FooCollection`1[AutomapperTest.Foo]

内部例外は次のように述べています。

{"Unable to cast object of type 'System.Collections.Generic.List`1[AutomapperTest.Foo]' to type 'AutomapperTest.IFooCollection`1[AutomapperTest.Foo]'."}

...最後に私の質問は次のとおりです。オートマッパーを取得して、コレクションをカスタムコレクションタイプにマップするにはどうすればよいですか? .AfterMap(..) を使用して手動で変換を正常に行うことができましたが、それがこの問題の意図した解決策であるかどうかわかりませんか?

4

0 に答える 0