1
を使用して、デフォルト値を持つマッピングプロパティを無視します。 source
オブジェクトからdestination
オブジェクトに、デフォルト以外の値を持つプロパティのみをマッピングする方法はありますか?は私が<code>destination</code>をオブジェクトへのオブジェクト<code>source</code>をマッピングするためにAutomapperを使用Automapper
を使用して、デフォルト値を持つマッピングプロパティを無視します。 source
オブジェクトからdestination
オブジェクトに、デフォルト以外の値を持つプロパティのみをマッピングする方法はありますか?は私が<code>destination</code>をオブジェクトへのオブジェクト<code>source</code>をマッピングするためにAutomapperを使用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);
}