我使用的是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...
这将生成一个将Street设置为null的user.Address对象实例。我宁愿让user.Address完全没有实例化。
答案 0 :(得分: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