Automapper 忽略空值,但将空字符串映射到空值
Automapper ignore null values but do map empty string to null
我们正在使用自动映射器。我想映射两个相同类型的对象。当源成员值 = null 时,应使用目标成员。但是,当源成员值为空字符串 ("") 时,我希望目标成员变为空。这是一个示例代码:
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);
}
但是这会失败。 mappedo.text 将是“非空”。你有什么建议如何实现当源成员为空字符串时所有字符串类型的成员都变为null?
更改条件即可解决问题:
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);
}
我们正在使用自动映射器。我想映射两个相同类型的对象。当源成员值 = null 时,应使用目标成员。但是,当源成员值为空字符串 ("") 时,我希望目标成员变为空。这是一个示例代码:
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);
}
但是这会失败。 mappedo.text 将是“非空”。你有什么建议如何实现当源成员为空字符串时所有字符串类型的成员都变为null?
更改条件即可解决问题:
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);
}