相同类型时AutoMapper无法正确映射 [英] AutoMapper not mapping correctly when same type

查看:207
本文介绍了相同类型时AutoMapper无法正确映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了AutoMapper(.NET 4.5上的3.1.1)库的问题,这很奇怪,我将感谢您的帮助.

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

我有四个物体:

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

在这种情况下:

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 :(

谢谢!

推荐答案

最后,我解决了这个问题,AutoMapper使用GetHashCode来确定两个对象是否相同,并且当我覆盖此方法时,在这种情况下,哈希码就是一样.

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.

这篇关于相同类型时AutoMapper无法正确映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆