AutoMapper无法映射参考或使用UseDestinationValue

时间:2019-06-15 15:05:26

标签: c# automapper

代码优先

class Woman
{
    public string Name { get; set; }
}
class Family
{
    public string SweetName { get; set; }
    public Woman Wife { get; set; }
}
class MyProfile : Profile
{
    public MyProfile()
    {
        CreateMap<Woman, Woman>();
        CreateMap<Family, Family>()
            .ForMember(d => d.Wife, o => o.UseDestinationValue());
    }
}
class Program
{
    static void main()
    {
        // Initialize
        var ce = new MapperConfigurationExpression();
        ce.AddProfile(new MyProfile());
        var mapper = new MapperConfiguration(ce).CreateMapper();

        var oldWoman = new Woman { Name = "Alice" };
        var newWoman = mapper.Map<Woman>(oldWoman);
        Console.WriteLine($"oldWoman.Equals(newWoman) : {oldWoman.Equals(newWoman)}");
        // false 

        var oldFamily = new Family { SweetName = "family one", Wife = oldWoman };
        var newFamily = mapper.Map<Family>(oldFamily);
        Console.WriteLine($"oldFamily.Equals(newFamily) : {oldFamily.Equals(newFamily)}"); 
        // false

        Console.WriteLine($"oldFamily.Wife.Equals(newFamily.Wife) : {oldFamily.Wife.Equals(newFamily.Wife)}"); 
        // false
        // here i wanna reference of oldfamily.wife pass to newfamily.wife's
    }
}

我已经设置了UseDestinationValue(),它不起作用吗?

如果我不创建女人图,那么两个妻子的参考是相等的。

像这样:

class MyProfile : Profile
{
    public MyProfile()
    {
        //CreateMap<Woman, Woman>();
        CreateMap<Family, Family>();
        //.ForMember(d => d.Wife, o => o.UseDestinationValue());
    }
}

PS。无需创建女性地图,并且UseDestinationValue是不必要的。无需创建女人图和使用UseDestinationValue方法,两个妻子的参考是相等的。

在这种情况下,如何通过使用创建女性班级地图来传递参考?

已更新1

解决这个问题的奇怪方法:

class MyProfile : Profile
{
    public MyProfile()
    {
        CreateMap<Woman, Woman>();
        CreateMap<Family, Family>()
            .AfterMap((s, d) => d.Wife = s.Wife);
    }
}

它有效,但是显然不是最终的方法。

已被映射。 XD

在执行意外的映射后会期望映射吗?

0 个答案:

没有答案