【问题标题】:Conditional property mapping in Automapper not workingAutomapper 中的条件属性映射不起作用
【发布时间】:2017-11-22 15:06:58
【问题描述】:

我正在使用 Automapper 6.2.0,并且我有以下类:

public class User
{
    public Address Address { get; set; }
}

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

public class UserDto
{
    public string AddressStreet { get; set; }
}

我的映射配置如下:

        CreateMap<UserDto, User>()
            .ForPath(dest => dest.Address.Street, opt => opt.Condition(cond => !string.IsNullOrEmpty(cond.Source.AddressStreet)))
            .ForPath(dest => dest.Address.Street, opt => opt.MapFrom(src => src.AddressStreet));

我像这样将 UserDto 映射到 User:

var userDto = new UserDto{ AddressStreet = null };
var user = mapper.Map<User>(userDto);
var address = user.Address;//I expect the prop to be null, since the mapping condition is not met...

这会生成一个 user.Address 对象实例,其中 Street 设置为 null。我宁愿 user.Address 根本不被实例化。

【问题讨论】:

  • 我也有同样的问题。人们会认为,当条件为假时,行为将与根本没有为 Address.Street 定义映射时相同。似乎是 Automapper 中的一个错误。
  • @thatWiseGuy 根据创作者的说法,这是设计使然...github.com/AutoMapper/AutoMapper/issues/2429

标签: c# automapper


【解决方案1】:

您的映射配置引发以下异常。

System.ArgumentException occurred
HResult=0x80070057
Message=Expression 'dest => dest.Address.Street' must resolve to top-
level member and not any child object's properties. You can use 
ForPath, a custom resolver on the child type or the AfterMap option 
instead.
Source=<Cannot evaluate the exception source>
StackTrace:
at AutoMapper.Internal.ReflectionHelper.FindProperty(LambdaExpression 
lambdaExpression)
at AutoMapper.Configuration.MappingExpression`2.ForMember[TMember]
(Expression`1 destinationMember, Action`1 memberOptions)
at NetCore.AutoMapperProfile..ctor()

请尝试以下映射配置:

CreateMap<UserDto, User>()
.ForMember(dest => dest.Address, opt => opt.Condition(src => !string.IsNullOrEmpty(src.AddressStreet)))
.ForMember(dest => dest.Address, opt => opt.MapFrom(src => src.AddressStreet));

以上将导致user.Address = null

【讨论】:

  • 我的错,我复制了错误的代码版本。现在改版了。
  • 您是正确的,上面的代码导致 user.Address 为空,但只要 userDto.AddressStreet 不为空,它就不起作用 - 异常是错误映射类型,因为 Address 是一个对象, AddressStreet 是一个字符串。
猜你喜欢
  • 1970-01-01
  • 2020-02-29
  • 2015-12-08
  • 2020-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多