如何在不创建新对象的情况下使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
类。
答案 0 :(得分:1)
解决此问题的一种方法是在构建ConstructUsing
期间使用Aprop
并设置C
:
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());
});
这应该有效,并且假设它只是一个属性而不是太痛苦。