UltraMapper
UltraMapper copied to clipboard
How to clone only selected properties
If I have a source object, how i clone only selected properties of it ,and set others to null after clone.
Hi. here is the basic example:
If your source object is initialized with null values, just ignore the properties you don't need as follows:
public class A
{
public int P1 { get; set; }
public string P2 { get; set; }
public List<string> P3 { get; set; }
public List<int> P4 { get; set; }
}
var mapper = new Mapper( cfg =>
{
cfg.MapTypes<A, A>()
.IgnoreSourceMember( s => s.P2 )
.IgnoreSourceMember( s => s.P4 );
} );
var target = mapper.Map( source );
Assert.IsTrue( target.P1 == source.P1 );
Assert.IsTrue( target.P2 == null );
Assert.IsTrue( target.P3.SequenceEqual( source.P3 ) );
Assert.IsTrue( target.P4 == null );
OR (if you have a lot of properties you want to ignore)
var mapper = new Mapper( cfg =>
{
cfg.MapTypes<A, A>( cfgType => cfgType.IgnoreMemberMappingResolvedByConvention = true )
.MapMember( s => s.P1, t => t.P1 )
.MapMember( s => s.P3, t => t.P3 )
} );
var target = mapper.Map( source );
Assert.IsTrue( target.P1 == source.P1 );
Assert.IsTrue( target.P2 == null );
Assert.IsTrue( target.P3.SequenceEqual( source.P3 ) );
Assert.IsTrue( target.P4 == null );
If you need to set the targets to null (because the properties are initialized to a value != null in the constructor or via initializers) you would need something like this (unfortunately setting to null is not supported at the moment in the current UltraMapper version).
public class AInitialized
{
public int P1 { get; set; }
public string P2 { get; set; }
public List<string> P3 { get; set; }
public List<int> P4 { get; set; } = new List<int>();
}
var mapper = new Mapper( cfg =>
{
cfg.MapTypes<AInitialized, AInitialized>()
.MapMember( s => s.P4, t => t.P4, s => null )
.IgnoreSourceMember( s => s.P2 );
} );
//OR
var mapper = new Mapper( cfg =>
{
cfg.MapTypes<AInitialized, AInitialized>( cfgType => cfgType.IgnoreMemberMappingResolvedByConvention = true )
.MapMember( s => s.P1, t => t.P1 )
.MapMember( s => s.P3, t => t.P3 )
.MapMember( s => s.P4, t => t.P4, s => null );
} );
var target = mapper.Map( source );
Assert.IsTrue( target.P1 == source.P1 );
Assert.IsTrue( target.P2 == null );
Assert.IsTrue( target.P3.SequenceEqual( source.P3 ) );
Assert.IsTrue( target.P4 == null );
I'll let you know when the feature is available by commenting to this post.
Hope it helps
Thank you very much, UltraMapper is wonderful, and you are so nice.