Automapper使用ValueResolver映射到自定义集合类型失败

时间:2014-02-26 09:29:07

标签: c# automapper automapper-3

我正在尝试映射一个包含泛型集合的类,并希望将该类映射到另一个类,其中该集合是另一个自定义类型。但是,当我尝试进行映射时,我得到一个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(..)手动成功完成转换,但我不确定这个问题的解决方案是什么?

0 个答案:

没有答案