2

我有这样的代码:

    //Fields
    Product _prod, _existingProd;

    void Test()
    {
        _prod = MakeAndPopulateSomeRandomProduct();
        _existingProd = GetProdFromDb(1);

        Mapper.CreateMap()
        .AfterMap((s, d) =>
        {
            Console.WriteLine(d==_existingProd); //Why does this print false?

            //Customize other properties on destination object
        });

    Mapper.Map(_prod, _existingProd);
}

当我打电话时Test()false会打印但我预期true。在我的场景中,能够object通过AfterMap参数访问原始目的地很重要。我只包含了用于演示问题的字段,但在我的真实代码中,我无法直接访问它们。Map()自定义映射时如何访问传入的对象实例?

4

1 回答 1

1

以下示例有效。可能您正在使用一些创建新实例的类型转换器......另外请提供所有映射配置以更好地理解问题。

[TestFixture]
public class AfterMap_Test
{
    //Fields
    private Product _prod, _existingProd;

    [Test]
    public void Test()
    {
        Mapper.CreateMap<Product, Product>()
            .AfterMap((s, d) =>
                          {
                              Trace.WriteLine(d == _existingProd); //Why does this print false?

                              //Customize other properties on destination object
                          });
        _existingProd = new Product {P1 = "Destination"};
        _prod = new Product {P1 = "Source"};
        Mapper.Map(_prod, _existingProd);
    }
}

internal class Product
{
    public string P1 { get; set; }
}
于 2012-11-06T20:11:33.280 回答