AutoMapper cannot mapping Reference or using UseDestinationValue

你说的曾经没有我的故事 提交于 2021-01-28 06:59:34

问题


Code First

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
    }
}

I have set UseDestinationValue(), it doesn't work?

if I don't create woman map, the two wife's reference is equal.

like this:

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

PS. no creating woman map and UseDestinationValue is unnecessary. two wife's reference is equal without creating woman map and using UseDestinationValue method.

How to pass the reference in this case with using create a map of woman class?

Updated 1

A strange way to solve this :

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

it works, but it's not the ultimate way obviously.

it has been mapped. XD

do expect mapping after doing unexpected mapping?

来源:https://stackoverflow.com/questions/56611542/automapper-cannot-mapping-reference-or-using-usedestinationvalue

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!