AutoMapper not mapping correctly when same type

▼魔方 西西 提交于 2019-12-23 05:47:07

问题


I got a problem with the AutoMapper (3.1.1 on .NET 4.5) library is very strange, i will appreciate your help.

I got four objects:

public class UserDetail
{
    public int Salary { get; set; }
    public Address House { get; set; }
    public Address Office { get; set; }
}

public class UserDetailEntity
{
    public int Salary { get; set; }
    public Guid HouseId { get; set; }
    public Guid? OfficeId { get; set; }
    public virtual AddressEntity House { get; set; }
    public virtual AddressEntity Office { get; set; }
}

public class Address
{
    public string Street { get; set; }
}

public class AddressEntity
{
    public string Street { get; set; }
}

And with this scenario:

Mapper.CreateMap<Address, AddressEntity>();
Mapper.CreateMap<UserDetail, UserDetailEntity>()
    .ForMember("Office", s => s.MapFrom(ud => ud.Office));


UserDetailEntity entity = Mapper.Map<UserDetail, UserDetailEntity>(dto);

Assert.AreEqual(dto.House.Street, entity.House.Street);
Assert.AreEqual(dto.Office.Street, entity.Office.Street);  

The Assert fails in the office address I always get the House address :(

Thank you!


回答1:


Finally I solve the problem, AutoMapper uses the GetHashCode to determine if two objects are the same, and as I override this method, on this scenario the hashcode is the same.



来源:https://stackoverflow.com/questions/21612176/automapper-not-mapping-correctly-when-same-type

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