1
我使用Automapper將對象source
映射到對象destination
。 有沒有什麼辦法可以映射,只有屬性有非默認值,從source
對象到destination
對象?使用Automapper忽略映射屬性與默認值
我使用Automapper將對象source
映射到對象destination
。 有沒有什麼辦法可以映射,只有屬性有非默認值,從source
對象到destination
對象?使用Automapper忽略映射屬性與默認值
的關鍵點是檢查源屬性的類型和僅當這些條件滿足映射(!= null
用於引用類型,!= default
爲一個值類型):
Mapper.CreateMap<Src, Dest>()
.ForAllMembers(opt => opt.Condition(
context => (context.SourceType.IsClass && !context.IsSourceValueNull)
|| (context.SourceType.IsValueType
&& !context.SourceValue.Equals(Activator.CreateInstance(context.SourceType))
)));
完整的解決方案是:
public class Src
{
public int V1 { get; set; }
public int V2 { get; set; }
public CustomClass R1 { get; set; }
public CustomClass R2 { get; set; }
}
public class Dest
{
public int V1 { get; set; }
public int V2 { get; set; }
public CustomClass R1 { get; set; }
public CustomClass R2 { get; set; }
}
public class CustomClass
{
public CustomClass(string id) { Id = id; }
public string Id { get; set; }
}
[Test]
public void IgnorePropertiesWithDefaultValue_Test()
{
Mapper.CreateMap<Src, Dest>()
.ForAllMembers(opt => opt.Condition(
context => (context.SourceType.IsClass && !context.IsSourceValueNull)
|| (context.SourceType.IsValueType
&& !context.SourceValue.Equals(Activator.CreateInstance(context.SourceType))
)));
var src = new Src();
src.V2 = 42;
src.R2 = new CustomClass("src obj");
var dest = new Dest();
dest.V1 = 1;
dest.R1 = new CustomClass("dest obj");
Mapper.Map(src, dest);
//not mapped because of null/default value in src
Assert.AreEqual(1, dest.V1);
Assert.AreEqual("dest obj", dest.R1.Id);
//mapped
Assert.AreEqual(42, dest.V2);
Assert.AreEqual("src obj", dest.R2.Id);
}