自动映射器UseDestinationValue不起作用 [英] Automapper UseDestinationValue not working

查看:74
本文介绍了自动映射器UseDestinationValue不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前正努力在同一类之间设置automapper.事情是我需要在调用 SaveOrUpdate()之前使用NHibernate从数据库获取实体.然后,我将替换除 Id LocationId 之外的所有属性.

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.

映射器:

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

映射器的用法

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

    m = meetingRoomMapper.MapFrom(meetingRoom);

    meetingRoomRepository.SaveOrUpdate(m);

    t.Commit();
}

当我调试代码时,我可以看到 m 填充了 locationId Id ,但是在映射器之后,它被< meetingRoom 的code> locationId 和 Id (默认为0).

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).

推荐答案

查看您要映射的线.

m = meetingRoomMapper.MapFrom(meetingRoom);

您要获取 meetingRoomMapper.MapFrom(meetingRoom)的结果并将其分配给 m .问题在于, meetingRoomMapper.MapFrom 甚至无法了解 m 的属性.您不能指望看起来像 m = ... 的行不会替换m表示的整个对象.

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

这篇关于自动映射器UseDestinationValue不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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