pandemic
pandemic

Reputation: 1195

Automapper UseDestinationValue not working

currently struggling with setting of automapper between same classes. The thing is I need to get the entity from db using NHibernate before calling the SaveOrUpdate(). I am then replacing all the properties except Id and LocationId.

Mapper:

public Domain.DomainObjects.Entities.MeetingRoom MapFrom(Domain.DomainObjects.Entities.MeetingRoom input)
        {
            if (!initialized)
            {
                lock (Sync)
                {
                    if (!initialized)
                    {
                        Mapper.CreateMap<Domain.DomainObjects.Entities.MeetingRoom, Domain.DomainObjects.Entities.MeetingRoom>()
                .ForMember(x => x.Id, opt => opt.UseDestinationValue())
                .ForMember(x => x.LocationId, opt => opt.UseDestinationValue());

                        initialized = true;
                    }
                }
            }

            if (input == null)
            {
                throw new NullReferenceException("MeetingRoom is not set!");
            }

            var result = (Domain.DomainObjects.Entities.MeetingRoom)Mapper.Map(input, input.GetType(), typeof(Domain.DomainObjects.Entities.MeetingRoom));

            return result;
        }

Usage of mapper

using (ITransaction t = NHibernateSession.Current.BeginTransaction())
{
    var m = meetingRoomRepository.FindAll(new MeetingRoomByEmailSpecification(meetingRoom.Email)).FirstOrDefault();

    m = meetingRoomMapper.MapFrom(meetingRoom);

    meetingRoomRepository.SaveOrUpdate(m);

    t.Commit();
}

when I am debugging the code I can see that m has the locationId and Id filled but after mapper its being overwriting with the locationId and Id of the meetingRoom (which is 0 by default).

Upvotes: 2

Views: 2122

Answers (1)

Look at the line you're using to map.

m = meetingRoomMapper.MapFrom(meetingRoom);

you're taking the result of meetingRoomMapper.MapFrom(meetingRoom) and assigning it to m. The problem is, that there's no way for meetingRoomMapper.MapFrom to even know about the properties of m. You can't expect a line that looks like m = ... to not replace the whole object represented by m.

Instead, You should look for a mapping function that takes a destination object as one of it's arguments.

m = Mapper.Map(meetingRoom, m);

Upvotes: 4

Related Questions