Skip to content

Instantly share code, notes, and snippets.

@PashaPash
Forked from lbargaoanu/AutoMapper.cs
Created December 25, 2024 01:22
Show Gist options
  • Save PashaPash/d169b2256b3c4075056e8c34defd0811 to your computer and use it in GitHub Desktop.
Save PashaPash/d169b2256b3c4075056e8c34defd0811 to your computer and use it in GitHub Desktop.
Sample AM
using AutoMapper;
interface IDestination
{
int SomeProp { get; }
}
class Destination : IDestination
{
public int SomeProp { get; set; }
}
class Source
{
public int SomeOther { get; set; } = 42;
}
class Program
{
static void Main()
{
var configurationNotMapped = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, IDestination>()
.ForMember(d => d.SomeProp, o => o.MapFrom(s => s.SomeOther));
cfg.CreateMap<Source, Destination>()
.IncludeBase<Source, IDestination>();
});
var configurationMapped = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, IDestination>()
.ForMember(d => d.SomeProp, o => o.MapFrom(s => s.SomeOther));
cfg.CreateMap<Source, Destination>()
// any mention of target property,
// for example .ForMember(d => d.SomeProp, o => o.ExplicitExpansion())
.ForMember(d => d.SomeProp, o => {})
.IncludeBase<Source, IDestination>();
});
configurationNotMapped.AssertConfigurationIsValid();
configurationMapped.AssertConfigurationIsValid();
var source = new Source();
// will output 0
Console.WriteLine(configurationNotMapped.CreateMapper()
.Map<Destination>(source).SomeProp);
// will output 42
Console.WriteLine(configurationMapped.CreateMapper()
.Map<Destination>(source).SomeProp);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment