Skip to content

Instantly share code, notes, and snippets.

@Vaccano
Last active December 21, 2015 15:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Vaccano/6324223 to your computer and use it in GitHub Desktop.
Save Vaccano/6324223 to your computer and use it in GitHub Desktop.
Automapper reusing the same instance
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