juan25d
juan25d

Reputation: 388

AutoMapper not mapping correctly when same type

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!

Upvotes: 1

Views: 1484

Answers (1)

juan25d
juan25d

Reputation: 388

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.

Upvotes: 3

Related Questions