Last active
December 21, 2015 15:08
-
-
Save Vaccano/6324223 to your computer and use it in GitHub Desktop.
Automapper reusing the same instance
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void Main() | |
{ | |
Mapper.CreateMap<SourceTest, DestTest>() | |
.ForMember(x=>x.CommonIgnoredValue, opt=>opt.Ignore()) | |
.IgnoreAllNonExisting(); | |
var source = new SourceTest{ CommonValue = "FromSource", CommonIgnoredValue = "Ignored Value from Source"}; | |
var dest = new DestTest { CommonValue = "FromDest", CommonIgnoredValue = "Ignored Value from Dest", DestOnlyValue = "Value Only In Dest" }; | |
Mapper.Map(source, dest); | |
// Outputs: | |
// CommonValue = FromSource | |
// CommonIgnoredValue = Ignored Value from Dest | |
// DestValueOnly = Value only in Dest | |
Console.WriteLine(dest); | |
} | |
public class SourceTest | |
{ | |
public string CommonValue {get; set;} | |
public string CommonIgnoredValue {get; set;} | |
} | |
public class DestTest | |
{ | |
public string CommonValue {get; set;} | |
public string CommonIgnoredValue {get; set;} | |
public string DestOnlyValue {get; set;} | |
} | |
public static class AutoMapperExtensions | |
{ | |
// Ignore any unmapped items that are in the destination. | |
public static IMappingExpression<TSource, TDestination> IgnoreAllNonExisting<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression) | |
{ | |
var sourceType = typeof(TSource); | |
var destinationType = typeof(TDestination); | |
var existingMaps = Mapper.GetAllTypeMaps().First(x => x.SourceType.Equals(sourceType) && x.DestinationType.Equals(destinationType)); | |
foreach (var property in existingMaps.GetUnmappedPropertyNames()) | |
{ | |
expression.ForMember(property, opt => opt.Ignore()); | |
} | |
return expression; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment