Reputation: 82
I have to cast two IEnumerables objects, let's call it Obj1 and Obj2.
To do this, i use automapper to cast directly the two lists, like this:
config = new MapperConfiguration(cfg => {
cfg.CreateMap<IEnumerable<Obj1>, IEnumerable<Obj2>>();
});
mapper = config.CreateMapper();
But i have a problem, because i want to give a default value to all the elements in the Obj2 list. Is there a way to do this keeping the IEnumerable cast?.
The only solution i have in mind is to create the mapper for the element itself and then iterate between all the elements in Obj1 list and cast to type Obj2, like this:
config = new MapperConfiguration(cfg => {
cfg.CreateMap<Obj1, Obj2>();
});
mapper = config.CreateMapper();
And then, in a foreach element in the list of Obj1, cast and add to a list of type Obj2.
I want to do this directly in the mapper configuration, is there a way to do it, keeping the IEnumerable mapping?.
Thanks.
Upvotes: 0
Views: 119
Reputation: 9463
If you have a map for the base objects, you do not need a map for collections of these objects. Instead, set the destination type when you call Map<TDestination>()
. See AutoMapper Docs: Lists and Arrays.
config = new MapperConfiguration(cfg => {
cfg.CreateMap<Obj1, Obj2>()
.ForMember(dest => dest.ShouldBeDefaulted,
o => o.MapFrom(src => src.ShouldBeDefaulted == null
? TheDefaultValue : src.ShouldBeDefaulted ));
});
var source = new List<Obj1>() { new Obj1("A"), new Obj1("B")};
// tell AutoMapper that the destination should be a collection during call to Map()
Obj2[] dest = mapper.Map<Obj2[]>(source);
Assert.AreEqual(2, dest.Length);
Upvotes: 1