Reputation: 6020
I'm mapping a pretty deeply nested entity to a flattened Dto
object and was wondering how I'd handle this gracefully with AutoMapper. I know I could null check each property as it's being mapped, but that's going to get VERY ugly for things like:
ForMember(s => s.Property, o => o.MapFrom(s => s.Parent.Child1.Child2.Child3.Property)
So I'm guess I could use various maps configs to the same destination object... but being relatively unskilled with AutoMapper I'm not sure what the performance implications of this are. What other, better, ways do I have of achieving what I want?
To re-iterate, I'm hoping to avoid something like this (I'm aware the below code probably doesn't compile... it's just an example) which I'd have to do for every member:
ForMember(s => s.Property, o => o.MapFrom(
s => s.Parent == null ? string.Empty :
s => s.Parent.Child1 == null ? string.Empty :
s => s.Parent.Child1.Child2 == null ? string.Empty :
s => s.Parent.Child1.Child2.Child3 == null ? string.Empty :
s => s.Parent.Child1.Child2.Child3.Property));
Upvotes: 9
Views: 5100
Reputation: 434
While this works for individual instances, it does not work for Projections on queryable collections.
This additional code I added to Andrew's answer fails miserably, even on the latest, 5.1.1 version.
var list = new List<Source>();
list.Add(new Source());
list.AsQueryable().ProjectTo<Dest>().Dump();
Example https://dotnetfiddle.net/Ecovrp
Upvotes: 2
Reputation: 126042
I think AutoMapper will actually handle null
propagation like this automatically for you. Your example:
ForMember(s => s.Property, o => o.MapFrom(s => s.Parent.Child1.Child2.Child3.Property)
should resolve to null
(I think), if any of the intermediate members are null
.
Example: https://dotnetfiddle.net/hMo3wa
Upvotes: 19