Skip to content

Instantly share code, notes, and snippets.

@ReeceDigital
Created March 7, 2023 10:48
Show Gist options
  • Save ReeceDigital/1944cfea50900de9feb83df8112e1266 to your computer and use it in GitHub Desktop.
Save ReeceDigital/1944cfea50900de9feb83df8112e1266 to your computer and use it in GitHub Desktop.
Gist for Automapper Discussion 4245
using AutoMapper;
public class Program
{
static void Main(string[] args)
{
try
{
var config = new MapperConfiguration(c =>
{
c.CreateMap<SourceCar, DestinationCar>()
.ForMember(dest => dest.Driver, opt => opt.MapFrom(src => src.Info.GeneralInfo));
c.CreateMap<SourceGeneralInfo, DestinationDriver>()
.IncludeMembers(src => src.Driver, src => src.Claim);
c.CreateMap<SourceDriver, DestinationDriver>()
.ForMember(dest => dest.DriverInfo, opt => opt.MapFrom(src => src));
c.CreateMap<SourceDriver, DestinationDriverInfo>()
.ForMember(dest => dest.NumberOfYearsDriving, opt => opt.MapFrom(src => src.NumDriving))
.ForMember(dest => dest.NumberOfClaims, opt => opt.Ignore());
c.CreateMap<SourceClaim, DestinationDriver>()
.ForMember(dest => dest.DriverInfo, opt => opt.MapFrom(src => src));
c.CreateMap<SourceClaim, DestinationDriverInfo>()
.ForMember(dest => dest.NumberOfClaims, opt => opt.MapFrom(src => src.NumClaims))
.ForMember(dest => dest.NumberOfYearsDriving, opt => opt.Ignore());
});
config.AssertConfigurationIsValid();
var mapper = config.CreateMapper();
var source = new SourceCar()
{
Info = new SourceInfo()
{
GeneralInfo = new SourceGeneralInfo()
{
Claim = new SourceClaim()
{
NumClaims = 1
},
Driver = new SourceDriver()
{
NumDriving = 2
}
}
}
};
var dest = mapper.Map<DestinationCar>(source);//.Dump();
}
catch (Exception ex)
{
ex.ToString();//.Dump();
}
}
}
public class SourceCar
{
public SourceInfo Info { get; set; }
}
public class SourceInfo
{
public SourceGeneralInfo GeneralInfo { get; set; }
}
public class SourceGeneralInfo
{
public SourceDriver Driver { get; set; }
public SourceClaim Claim { get; set; }
}
public class SourceDriver
{
public int NumDriving { get; set; }
}
public class SourceClaim
{
public int NumClaims { get; set; }
}
public class DestinationCar
{
public DestinationDriver Driver { get; set; }
}
public class DestinationDriver
{
public DestinationDriverInfo DriverInfo { get; set; }
}
public class DestinationDriverInfo
{
public int NumberOfYearsDriving { get; set; }
public int NumberOfClaims { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment