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]'."}

...所以最后我的问题是:我如何让 automapper 将集合映射到我的自定义集合类型?我可以使用 .AfterMap(..) 手动成功地进行转换,但我不确定这是这个问题的预期解决方案吗?

4

0 回答 0