0

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?

鐘冠武
  • 1
  • 1
  • If you don't want to map anything to `UserName`, then why have you configured the mapper to map it? Also, your condition ignores `null` values but it looks to me that your source value can never be null (though I'm not 100% sure how AutoMapper works!). – Charles Mager Aug 01 '17 at 15:49
  • Note that test sample is not very good - you have same id and same title. It's hard to see that mapping actually happens – Sergey Berezovskiy Aug 01 '17 at 16:14

2 Answers2

4

You can put condition to member configuration expression:

   .ForMember(dest => dest.UserName, opt => {
       opt.Condition(s => s.FirstName != null && s.LastName != null); // condition here
       opt.MapFrom(s => s.FirstName + " " + s.LastName);
   }); // remove all members condition

Note that possibly you should check not only for null but for empty values as well using String.IsNullOrEmpty or String.IsNullOrWhitespace

Output:

{
  "Id": 0,
  "Title": "blablabla",
  "UserName": "Foo Bar"
}
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
0

In the case your FirstName and LastName are null, then the srcMember will be a space - " ". As a result, your condition is matched.

You either need to change your projection to return null in the case both parts are null, or you need to change your condition to match the space.

Charles Mager
  • 25,735
  • 2
  • 35
  • 45