Reputation: 169
I have a scenario like
If total number of days is less than 30 days, then I have to set Salary to null
this.CreateMap<Foo, Doo>()
.ForMember(dst => dst.Salary, opt => {
opt.Condition(src => src.JoinedDate.Days <= 30));
opt.MapFrom(null)
}
But I am facing error "cannot find member of type Foo. Parameter name: name". but don't have any property "name".
Question is How to pass null value to destination property in condition check, and retain existing value if days greater than 30.
opt.MapFrom(null)
Upvotes: 1
Views: 374
Reputation: 169
I just combined above two solutions and found answer for my question.
ForMember(dst => dst.Salary,
opt => opt.ResolveUsing((src, dst) => src.JoinedDate.Days <= 30 ? null: dst.Salary));
Upvotes: 1
Reputation: 143033
Try using:
this.CreateMap<Foo, Doo>()
.ForMember(dst => dst.Salary,
opt => opt.MapFrom(src => src.JoinedDate.Days <= 30 ? null : src.Salary))
UPD
To preserve Salary
from destination use overload of MapFrom
accepting both source and destination:
this.CreateMap<Foo, Doo>()
.ForMember(dst => dst.Salary,
opt => opt.MapFrom((src, dst) => src.JoinedDate.Days <= 30 ? null : dst.Salary))
Upvotes: 2
Reputation: 4598
You can use automapper inline ResolveUsing
.
ForMember(dst => dst.Salary,
o => o.ResolveUsing(src => src.JoinedDate.Days > 30 ? src.Salary: null));
Upvotes: 1