Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't access automapper context items after upgrade to 9

Tags:

c#

automapper

I have a mapper like this:

CreateMap<Source, ICollection<Dest>>()
    .ConvertUsing((src, dst, context) => 
    {
        return context.Mapper.Map<ICollection<Dest>>
            (new SourceItem[] { src.Item1, src.Item2 ... }.Where(item => SomeFilter(item)),
            opts => opts.Items["SomethingFromSource"] = src.Something);
    });

CreateMap<SourceItem, Dest>()
    .ForMember(d => d.Something, opts => opts.MapFrom((src, dst, dstItem, context)
        => (string)context.Items["SomethingFromSource"]));

This gives me an exception saying You must use a Map overload that takes Action<IMappingOperationOptions>. Well, I do use the Map overload that takes this action. How else can I do this?

like image 556
Morse Avatar asked Feb 03 '26 11:02

Morse


2 Answers

This is because of this change:
https://github.com/AutoMapper/AutoMapper/pull/3150

You can get the the Items by accessing the ResolutionContext's Options property.

Change context.Items["SomethingFromSource"] to context.Options.Items["SomethingFromSource"].

When there is no Items, the ResolutionContext is the same with DefaultContext. Therefore The ResolutionContext.Items property will throw the exception.
However, if there is, the ResolutionContext.Items wouldn't be the same with DefaultContext. Therefore the ResolutionContext.Items will return the list.

While ResolutionContext.Options.Items will always return the list, it would not throw any exception, whether it's empty or not. I believe it's what the error message meant, because ResolutionContext.Options is an IMappingOperationOptions


Edited 21/08/2023: above was written prior to AutoMapper 12. For 12 and later, see @Pieter Riesz answer below. Thanks @Stoyan Dimov and @Peter Riesz for the update.

like image 174
Bowo Avatar answered Feb 05 '26 01:02

Bowo


Before v12.0.0

You can get the the Items by accessing the ResolutionContext's Options property.

 => context.Options.Items["SomethingFromSource"]

v12.0.0

In version 12.0.0 the Options was removed, you need to upgrade.

v12.0.1

You can use TryGetItems if you want to check whether a context was passed in the Map call.

 => context.TryGetItems(out var items) ? (string)items["SomethingFromSource"] : null

https://docs.automapper.org/en/latest/12.0-Upgrade-Guide.html

like image 39
Peter Riesz Avatar answered Feb 05 '26 01:02

Peter Riesz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!