C# 如何使Automapper在不创建新对象的情况下使用精确值

C# 如何使Automapper在不创建新对象的情况下使用精确值,c#,automapper,C#,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;

如何使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
        }
    }
}
使用System.Collections.Generic;
使用自动制版机;
名称空间程序
{
公共A类{}
公共B级
{
公共A Aprop{get;set;}
}
公共C类
{
公共A Aprop{get;set;}
}
班级计划
{
私有静态void Main(字符串[]args)
{
AutoMapper.Mapper.Initialize(cnf=>
{
//我真的需要这个映射。这里有一些额外的忽略。
CreateMap();
//应该以某种方式配置下一个映射
cnf.CreateMap();//.formMember(d=>d.Aprop,opt=>opt.MapFrom(…)???
});
A=新的A();
B=新的B(){Aprop=a};
C=映射器.Map(b);
var refToSameObject=b.Aprop.Equals(c.Aprop);//计算结果为false
}
}
}

我应该如何更改
cnf.CreateMap()行以使
refToSameObject
变量具有
true
值?如果我删除
cnf.CreateMap()
它将以这种方式工作,但是我无法删除它,因为有时我使用automapper从其他
A
类更新
A
类。

一种解决方法是在
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());
});
AutoMapper.Mapper.Initialize(cnf=>
{
CreateMap();
cnf.CreateMap()
.ConstructUsing(src=>newc(){Aprop=src.Aprop})
.ForMember(dest=>dest.Aprop,opt=>opt.Ignore());
});
这应该是可行的,假设它只是一个属性,也不会太痛苦