2016-12-14 82 views
1

如何使Automapper在不創建新對象的情況下使用精確值?如何使Automapper在不創建新對象的情況下使用精確值

using System.Collections.Generic; 
using AutoMapper; 

namespace Program 
{ 
    public class A { } 

    public class B 
    { 
     public A Aprop { get; set; } 
    } 

    public class C 
    { 
     public A Aprop { get; set; } 
    } 

    class Program 
    { 
     private static void Main(string[] args) 
     { 
      AutoMapper.Mapper.Initialize(cnf => 
      { 
       // I really need this mapping. Some additional Ignores are present here. 
       cnf.CreateMap<A, A>(); 
       // The next mapping should be configured somehow 
       cnf.CreateMap<B, C>(); //.ForMember(d => d.Aprop, opt => opt.MapFrom(...)) ??? 
      }); 
      A a = new A(); 
      B b = new B() {Aprop = a}; 
      C c = Mapper.Map<C>(b); 
      var refToSameObject = b.Aprop.Equals(c.Aprop); // Evaluates to false 
     } 
    } 
} 

我應該如何改變,以使cnf.CreateMap<B, C>();refToSameObject變量有true價值?如果我刪除cnf.CreateMap<A, A>();它將以這種方式工作,但我無法刪除它,因爲有時我會使用automapper從其他A類更新A類。解決此

回答

1

一種方式是C施工過程中使用ConstructUsing並設置Aprop

AutoMapper.Mapper.Initialize(cnf => 
{ 
    cnf.CreateMap<A, A>(); 
    cnf.CreateMap<B, C>() 
     .ConstructUsing(src => new C() { Aprop = src.Aprop }) 
     .ForMember(dest => dest.Aprop, opt => opt.Ignore()); 
}); 

這應該工作,是不是太痛苦的假設它真的只是一個屬性。

相關問題