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?

2
  • 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!). Commented Aug 1, 2017 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 Commented Aug 1, 2017 at 16:14

2 Answers 2

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"
}
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.