将对象传递给AutoMapper映射

CWi*_*tty 31 c# automapper asp.net-mvc-4

我正在使用AutoMapper,正在映射的实体的一些值是我当前方法中的变量.我试过谷歌它但无济于事.我可以将一组KeyValue对或一个对象或东西传递给我的映射以使其使用这些值吗?

后映射修改示例

//comment variable is a Comment class instance
var imageComment = AutoMapper.Mapper.Map<Data.ImageComment>(comment);
//I want to pass in imageId so I dont have to manually add it after the mapping
imageComment.ImageId = imageId;
Run Code Online (Sandbox Code Playgroud)

Jim*_*ard 40

AutoMapper开箱即可处理这个键值对场景.

Mapper.CreateMap<Source, Dest>()
    .ForMember(d => d.Foo, opt => opt.ResolveUsing(res => res.Context.Options.Items["Foo"]));
Run Code Online (Sandbox Code Playgroud)

然后在运行时:

Mapper.Map<Source, Dest>(src, opt => opt.Items["Foo"] = "Bar");
Run Code Online (Sandbox Code Playgroud)

有点冗长,深入研究上下文项目,但你去了.

  • 我在res.Context中遇到错误 - 源模型不包含上下文的定义.使用.net core 2.0和AutoMapper 6.2.1 (6认同)

Les*_*k P 33

对于Automapper 6.0.2:

轮廓:

public class CoreProfile : Profile
{
    public CoreProfile()
    {
        CreateMap<Source, Dest>()
            .ForMember(d => d.Foo,
                opt => opt.ResolveUsing(
                    (src, dst, arg3, context) => context.Options.Items["Foo"]
                )
            );
    }
}
Run Code Online (Sandbox Code Playgroud)

制图:

    var result = Mapper.Map<PlanResult>(aa, opt => {
        opt.Items["Foo"] = 2;
        opt.Items["OtherFoo"] = 1000;
    });
Run Code Online (Sandbox Code Playgroud)


MUG*_*G4N 33

自动映射器 9.0.0

从 8.0.0 版本开始,AutoMapper 的 API 已更改。这样做ResolveUsing被合并了MapFrom。查看相应的拉取请求以获取更多信息。

轮廓

public class CoreProfile : Profile
{
    public CoreProfile()
    {
        CreateMap<Source, Destination>()
            .ForMember(d => d.Bar,
                opt => opt.MapFrom(
                    (src, dst, _, context) => context.Options.Items["bar"]
                )
            );    
    }
}
Run Code Online (Sandbox Code Playgroud)

映射

var destination = mapper.Map<Destination>(
    source,opt => {
        opt.Items["bar"] = "baz";
    }
);
Run Code Online (Sandbox Code Playgroud)

  • 如果您能写几句话来说明与之前的答案(Automapper 6.0.2)相比发生了什么变化,那就太好了。 (2认同)
  • 在 Automapper 12.0.0 中,“context”没有“Options”属性。相反,使用“context.Items”。 (2认同)

mar*_*iro 6

可以使用ItemsDictionary 选项将对象传递给解析器。执行此操作的标准 API 非常冗长(如已接受的答案所示),但可以使用一些扩展方法很好地简化:

/// <summary>
/// Map using a resolve function that is passed the Items dictionary from mapping context
/// </summary>
public static void ResolveWithContext<TSource, TDest, TMember, TResult>(
    this IMemberConfigurationExpression<TSource, TDest, TMember> memberOptions, 
    Func<TSource, IDictionary<string, object>, TDest, TMember, TResult> resolver
) {
    memberOptions.ResolveUsing((src, dst, member, context) => resolver.Invoke(src, context.Items, dst, member));
}

public static TDest MapWithContext<TSource, TDest>(this IMapper mapper, TSource source, IDictionary<string, object> context, Action<IMappingOperationOptions<TSource, TDest>> optAction = null) {
    return mapper.Map<TSource, TDest>(source, opts => {
        foreach(var kv in context) opts.Items.Add(kv);
        optAction?.Invoke(opts);
    });
}
Run Code Online (Sandbox Code Playgroud)

可以这样使用:

// Define mapping configuration
Mapper.CreateMap<Comment, ImageComment>()
    .ForMember(
        d => d.ImageId,
        opt => opt.ResolveWithContext(src, items, dst, member) => items["ImageId"])
    );

// Execute mapping
var context = new Dictionary<string, object> { { "ImageId", ImageId } };
return mapper.MapWithContext<TSource, TDest>(source, context);
Run Code Online (Sandbox Code Playgroud)

如果您有一个通常需要传递给映射器解析器的对象(例如,当前用户),您可以更进一步并定义更专业的扩展:

public static readonly string USER_CONTEXT_KEY = "USER";

/// <summary>
/// Map using a resolve function that is passed a user from the
/// Items dictionary in the mapping context
/// </summary>
public static void ResolveWithUser<TSource, TDest, TMember, TResult>(
    this IMemberConfigurationExpression<TSource, TDest, TMember> memberOptions,
    Func<TSource, User, TResult> resolver
) {
    memberOptions.ResolveWithContext((src, items, dst, member) =>
        resolver.Invoke(src, items[USER_CONTEXT_KEY] as User));
}

/// <summary>
/// Execute a mapping from the source object to a new destination
/// object, with the provided user in the context.
/// </summary>
public static TDest MapForUser<TSource, TDest>(
    this IMapper mapper,
    TSource source,
    User user,
    Action<IMappingOperationOptions<TSource, TDest>> optAction = null
) {
    var context = new Dictionary<string, object> { { USER_CONTEXT_KEY, user } };
    return mapper.MapWithContext(source, context, optAction);
}
Run Code Online (Sandbox Code Playgroud)

可以像这样使用:

// Create mapping configuration
Mapper.CreateMap<Source, Dest>()
    .ForMember(d => d.Foo, opt => opt.ResolveWithUser((src, user) src.Foo(user));

// Execute mapping
return mapper.MapWithUser(source, user);
Run Code Online (Sandbox Code Playgroud)

  • 您可能想要更新 8.0 的答案,因为用 `MapFrom` 替换了 `ResolveUsing` http://docs.automapper.org/en/latest/8.0-Upgrade-Guide.html#resolveusing (3认同)