2012-11-06 38 views
2

我有這樣的代碼:AutoMapper:無法從內部AfterMap訪問)傳遞到地圖(原始對象實例()

//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。在我的情況下,能夠通過AfterMap參數訪問原始目標object非常重要。我只包含了這些字段來展示問題,但在我的真實代碼中,我沒有直接訪問它們。自定義映射時,如何訪問傳遞到Map()的對象實例?

回答

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; } 
} 
+0

謝謝k0stya,我試過你的例子,它也適用於我。我需要找出我的代碼似乎沒有工作的原因,並會考慮您的建議。 –