具有复杂配置的自动映射器

时间:2015-10-31 14:48:13

标签: c# automapper

我有一个json对象

{
  "userId": 12,
  "email": "demo@example.com",
  "firstName": "John",
  "lastName": "Smith",
  "customerName": "Microsoft"
  "contents": [
    {
      "productId": 34,
      "productName": "Product 1",
      "productCost": "35.50",
      "quantity": 3
    },
    {
      "productId": 35,
      "productName": "Product 2",
      "productCost": "40.99",
      "quantity": 1
    }
  ]
}

我发布到WebApi

public IHttpActionResult Post(ShoppingCartDto shoppingCart)
        {    
            var result = _service.AddToCart(shoppingCart);
            return Ok(result);
        }

然后我使用automapperShoppingCartDto映射到所有正确的域类。

所以这就是问题,如何在我实际到映射之前先使用automapper去查找customerIdenter image description here

我必须从customerId查找Customer table,以便当我映射到令牌表时,我有customerId

到目前为止的映射

Mapper.CreateMap<ShoppingCartDto, User>()
    .ForMember(dest => dest.UserId, opt => opt.MapFrom(src => src.UserId))
    .AfterMap((src, dest) =>
    {
        var token = (Mapper.Map<Token>(dest));

        token.CustomerId = "Can I do database lookup here" 

        dest.Tokens.Add(token);

        foreach (var content in Mapper.Map<Cart[]>(src.Contents))
        {
            token.Contents.Add(content);
        }
    });

或者我应该使用某种自定义解析器。

我的映射位于AutoMapperConfig文件夹内的App_Start文件中。所以我不是100%肯定如何去做。我知道我可以手动进行映射,但我想保留Automapper

的所有映射

1 个答案:

答案 0 :(得分:2)

由于您的映射过程需要访问某些服务(在您的情况下是数据访问),因此最好将映射过程封装在某些服务中,如下所示:

public interface IMapper<TSource, TDestination>
{
    TDestination Map(TSource source);
}

public class ShoppingCartDtoToUserMapper : IMapper<ShoppingCartDto, User>
{
    private IDataAccessor m_DataAccessor; //This can be a repository for example, I am just using IDataAccessor as an example

    public ShoppingCartDtoToUserMapper(IDataAccessor data_accessor)
    {
        m_DataAccessor = data_accessor;
    }

    public User Map(ShoppingCartDto source)
    {
        //Use AutoMapper here as you did and also use m_DataAccessor for any data access operations
    }
}

您应该使用dependency injection来正确构建ShoppingCartDtoToUserMapper依赖项并将其(作为IMapper<ShoppingCartDto, User>)注入需要从ShoppingCartDto到{{1}的映射功能的类中}。