Check for empty context #4125
-
Like indicated in the upgrade guide, I can create a PR to return an empty dictionary instead of raising an exception but it would introduce another breaking change. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 4 replies
-
If you need the context, you're supposed to call a |
Beta Was this translation helpful? Give feedback.
-
I've just ran into the same thing, I have a lot of code that does ContainsKey checking. In some instances if that key doesn't exist it does some expensive calculations to set it in a BeforeMap so that the various properties that use that expensive result can use a cached version. I'm not sure of any way to do something similar to the following without changing all the calls to map, which is a bit frustrating: CreateMap<Foo, Bar>()
.BeforeMap(foo, bar, context) =>{
if(!context.Items.ContainsKey("ExpensiveResult"))
context.Items.Add("ExpensiveResult", DoExpensiveThing(foo));
})
.ForMember(b => b.Thing, opt => opt.MapFrom((_,_,_, context) => context.Items["ExpensiveResult"]))
.ForMember(b => b.OtherThing, opt => opt.MapFrom((_,_,_, context) => context.Items["ExpensiveResult"] / 2)) Granted doing that expensive operation and passing it in when calling |
Beta Was this translation helpful? Give feedback.
-
https://docs.automapper.org/en/latest/Flattening.html#includemembers |
Beta Was this translation helpful? Give feedback.
If you need the context, you're supposed to call a
Map
overload with options. But yes, there is no way to call without options and then check without throwing. I suggest that you simply pay for the extra allocations and always call with options. Or use some other way to pass state, withIncludeMembers
, in the source or destination object or through DI.I'd rather not add a flag for the sole purpose of telling you there is no context.