C# Can';升级到9后,无法访问自动映射上下文项

C# Can';升级到9后,无法访问自动映射上下文项,c#,automapper,C#,Automapper,我有一个像这样的制图器: CreateMap<Source, ICollection<Dest>>() .ConvertUsing((src, dst, context) => { return context.Mapper.Map<ICollection<Dest>> (new SourceItem[] { src.Item1, src.Item2 ... }.Where(item

我有一个像这样的制图器:

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"]));
CreateMap()
.ConvertUsing((src、dst、context)=>
{
返回context.Mapper.Map
(新的SourceItem[]{src.Item1,src.Item2…}.Where(item=>SomeFilter(item)),
opts=>opts.Items[“SomethingFromSource”]=src.Something);
});
CreateMap()
.ForMember(d=>d.Something,opts=>opts.MapFrom((src、dst、dstItem、context)
=>(字符串)context.Items[“SomethingFromSource”]);

这给了我一个异常,它说
您必须使用一个执行操作的Map重载。我确实使用了执行此操作的
Map
重载。我还能怎么做呢?

使用内部映射器(即
context.mapper
)时需要考虑的几个问题

首先,尽量不要使用
context.Mapper.Map(…)
,而是使用
context.Mapper.Map(…)
,因为它的性能更好

其次,在内部映射程序中使用上下文将破坏封装。如果需要在内部对象中设置值,请考虑这两种解决方案:

如果要在内部贴图之后设置值

context.Mapper.Map<Source, Dest> (source, opts => opts.AfterMap((s, d) => 
    d.Something = source.Something))
context.Mapper.Map<Source, Dest> (source, new Dest()
    {
        Something = source.Something
    })
context.Mapper.Map(source,opts=>opts.AfterMap((s,d)=>
d、 某物(来源,某物)
如果要在内部贴图之前设置值

context.Mapper.Map<Source, Dest> (source, opts => opts.AfterMap((s, d) => 
    d.Something = source.Something))
context.Mapper.Map<Source, Dest> (source, new Dest()
    {
        Something = source.Something
    })
context.Mapper.Map(源,新目标()
{
某物=来源,某物
})

这是因为这个变化:

您可以通过访问ResolutionContext的Options属性来获取项目

context.Items[“SomethingFromSource”]
更改为
context.Options.Items[“SomethingFromSource”]

没有项目时,
ResolutionContext
DefaultContext
相同。因此,
ResolutionContext.Items
属性将抛出异常。
但是,如果存在,则
ResolutionContext.Items
将与
DefaultContext
不同。因此,
ResolutionContext.Items
将返回列表


虽然
ResolutionContext.Options.Items
将始终返回列表,但它不会抛出任何异常,不管它是否为空。我相信这就是错误消息的意思,因为
ResolutionContext.Options
是一个
IMappingOperationOptions

使用此地图的每个呼叫站点都必须使用这样的重载。@LucianBargaoanu你是说外部地图吗?但我不需要这些选项,我没有任何东西可以从外部解释。它看起来像
mapper.Map(source,opts=>{})
。是的,或者更好,只需在Map调用中设置该项,而不是在Map中。映射器的整个思想是将映射细节隐藏在其中,而不是将其带到业务层中。此外,还可以从多个位置调用映射器。如果我需要更改映射详细信息,我将不得不处理所有调用。最后,如果我编写了一个映射程序,将它作为一个组件使用,我将无法正确设置上下文。那么您只需要使用正确的重载。工作得很好,谢谢。context.Options.Items.ContainsKey(…)将context.Items[“…”]更改为context.Options.Items[“.”意味着异常变得更有意义。谢谢