1
votes

I am trying to mapping a entity in another with similar properties but I would like to have a field more in my "destination type". I want to map a Entity that use the destination value for a null field of the source class and I don´t want to have all fields mapped on my source type.

Have a look at the example:

[TestClass]
public class Example
{
  public class Person
  {
      public string FirstName { get; set; }
      public string LastName { get; set; }
      public int? Foo { get; set; }
  }

  public class DPerson
  {
      public string FirstName { get; set; }
      public string LastName { get; set; }
      public int? Foo { get; set; }
      public bool IsUser { get; set; }
  }

  [TestMethod]
  public void TestNullIgnore()
  {
      Mapper.CreateMap<Person, DPerson>()
          .ForAllMembers(opt => opt.Condition(srs => !srs.IsSourceValueNull));

      var sourcePerson = new Person
      {
          FirstName = "Bill",
          LastName = "Gates",
      };
      var destinationPerson = new DPerson
      {
          FirstName = "",
          LastName = "",
          Foo = 1,
          IsUser = true
      };
      Mapper.Map(sourcePerson, destinationPerson);

      Assert.IsNotNull(destinationPerson);
      Assert.AreEqual(1, destinationPerson.Foo);
      Assert.AreEqual(true, destinationPerson.IsUser);
  }
} 

When I added IsUser property at DPerson class The AutoMapper throws an odd exception "AutoMapper.AutoMapperMappingException" and in its message it said that it is not possible to map "Person -> Boolean".

If I remove ".ForAllMembers(opt => opt.Condition(srs => !srs.IsSourceValueNull))" configuration it works but I got "null" at the Foo property.

I adpated the code of the first answer for this question: AutoMapper.Map ignore all Null value properties from source object

Can anyone help me?

Cheers.

1

1 Answers

0
votes

The error message is odd--but it does make sense that IsSourceValueNull is not working in this particular case. Since IsUser is of type bool, its value can never be null.

This means that when AutoMapper evaluates IsSourceValueNull for that property, it's getting "false" every time for the IsUser property. Then, it tries to map the IsUser property and fails.

One way to fix this is to explicitly ignore the IsUser property:

Mapper.CreateMap<Person, DPerson>()
    .ForMember(dest => dest.IsUser, opt => opt.Ignore())         
    .ForAllMembers(opt => opt.Condition(srs => !srs.IsSourceValueNull));