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.