将对象传递给AutoMapper映射

时间:2015-07-31 14:29:57

标签: c# asp.net-mvc-4 automapper

我正在使用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;

5 个答案:

答案 0 :(得分:36)

AutoMapper handles this key-value pair scenario out of the box.

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

Then at runtime:

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

A bit verbose to dig into the context items but there you go.

答案 1 :(得分:32)

对于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"]
                )
            );
    }
}

<强>映射:

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

答案 2 :(得分:16)

AutoMapper 9.0.0

从8.0.0版开始,AutoMapper的API已更改。为此,ResolveUsing已与MapFrom合并。请查看相应的pull request,以获取更多信息。

个人资料

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

映射

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

答案 3 :(得分:3)

可以使用Items词典选项将对象传递到解析器。执行此操作的标准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);
    });
}

可以这样使用:

// 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);

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

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);
}

可以这样使用:

// 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);

答案 4 :(得分:-1)

假设您有这两个对象:

public class ObjectA {
 public string Property1 { get; set; }
 public int Property2 { get; set; }
}
public class ObjectB {
 public string Property1 { get; set; }
 public int Property2 { get; set; }
}

并且您希望将类型为ObjectA的现有对象复制到ObjectB类型的新对象中,使用AutoMapper必须执行此操作:

var objectA = new ObjectA { Property1 = "Hello, World!", Property2 = 1 }
var objectB = new ObjectB();

// Copy data from a to b
AutoMapper.Mapper
  .CreateMap<ObjectA, ObjectB>()
  .BeforeMap((source, dest) => { dest.ImageId = imageId });
AutoMapper.Mapper.Map(objectA, objectB); // source, destination;

// Or:
var objectB = AutoMapper.Mapper.Map<ObjectB>(objectA);