问题
Is it possible to map from a property of type Collection<T> to another property of type Collection<T> by convention without the need to define the mapping explicitly?
class CollectionExample {
public static void Example() {
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Foo, FooDto>()
//.ForMember(dest => dest.Items, member => member.MapFrom(src => src.Items))
;
});
var mapper = config.CreateMapper();
var foo = new Foo() {
Items =
{
new Foo(),
new Foo(),
new Foo()
}
};
var fooDto = mapper.Map<Foo, FooDto>(foo);
Debug.Assert(fooDto.Items.Count == foo.Items.Count, $"There are only {fooDto.Items.Count} items in the dto object but we expected {foo.Items.Count} items.");
}
class Foo {
public Collection<Foo> Items { get; } = new Collection<Foo>();
}
class FooDto {
public Collection<FooDto> Items { get; } = new Collection<FooDto>();
}
}
When I uncomment the ForMember(..)
this works. Am I missing something for the convention based method?
回答1:
You need either a setter, or the MapFrom
, whichever you prefer :)
来源:https://stackoverflow.com/questions/58752261/mapping-from-collectiont-to-collectiont-by-convention