pkmetski
pkmetski

Reputation: 171

Conditional property mapping in Automapper not working

I am using Automapper 6.2.0 and I have the following classes:

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

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

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

My mapping is configured as follows:

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

I map UserDto to User like so:

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

This produces a user.Address object instance with Street set to null. I would rather have user.Address not be instantiated at all.

Upvotes: 1

Views: 2180

Answers (1)

Chandan Rauniyar
Chandan Rauniyar

Reputation: 824

Your mapping configuration throws following exception.

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

Try the following Mapping configuration instead:

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

The above will result in user.Address = null

Upvotes: 1

Related Questions