2016-12-14 55 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()); 
}); 

这应该工作,是不是太痛苦的假设它真的只是一个属性。

相关问题