First of all, English is not my mother tongue, so please excuse me.
Source Model:
public class Task
{
public int Id { get; set; }
public string Title { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
Destination Model:
public class Task2
{
public int Id { get; set;}
public string Title { get; set; }
public string UserName { get; set; }
}
Mapping:
CreateMap<Task, Task2>()
.ForMember(dest => dest.UserName, opt => opt.MapFrom(s => s.FirstName + " " + s.LastName))
.ForAllMembers(opt => opt.Condition((src, dest, srcMember) => srcMember != null));
And now, the problem is:
Task t = new Task(){
Id = 0,
Title = "blablabla",
FirstName = null,
LastName = null
}
Task2 t2 = new Task2(){
Id = 0,
Title = "blablabla",
UserName = "Foo Bar"
}
Task2 tt = Mapper.Map<Task, Task2>(t, t2);
After Mapping, the tt.UserName will be Empty.
I want to keep the value of Task2.UserName, but it seems doesn't work. How Can I do?
UserName, then why have you configured the mapper to map it? Also, your condition ignoresnullvalues but it looks to me that your source value can never be null (though I'm not 100% sure how AutoMapper works!).