Reputation: 31
We are using automapper. I want to map two objects of the same type. When the source member value = null, then the destination member should be used. However when the source member value is an empty string (""), I want the destination member to become null. Here is an example code:
public class someobject
{
public string text { get; set; }
}
[TestMethod]
public void EmptyStringMap()
{
var cfg = new MapperConfiguration(c => c.CreateMap<someobject, someobject>()
.AddTransform<string>(s => string.IsNullOrEmpty(s) ? null : s)
.ForAllOtherMembers(o =>
o.Condition((src, dest, srcmember) => srcmember != null)));
var map = cfg.CreateMapper();
var desto = new someobject() { text = "not empty" };
var srco = new someobject() { text = "" };
var mappedo = map.Map(srco, desto);
Assert.IsNull(mappedo.text);
}
This however will fail. mappedo.text will be "not empty". Do you have a suggestion how to achieve all members of type string to become null when the source member is an empty string?
Upvotes: 0
Views: 3210
Reputation: 31
Changing the conditions will do the trick:
public class someobject
{
public string text { get; set; }
}
[TestMethod]
public void EmptyStringMap()
{
var cfg = new MapperConfiguration(c => {
c.CreateMap<someobject, someobject>()
.AddTransform<string>(s => string.IsNullOrEmpty(s) ? null : s)
.ForAllOtherMembers(o =>
o.Condition((src, dest, srcmember, destmember) => srcmember != null || destmember.GetType() == typeof(string)));
});
var map = cfg.CreateMapper();
var desto = new someobject() { text = "not empty" };
var srco = new someobject() { text = "" };
//var srco = new someobject() { text = null };
var mappedo = map.Map(srco, desto);
Assert.IsNull(mappedo.text);
}
Upvotes: 2