Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
using System.ComponentModel;
using System.Reflection;
using System.Data;
using System;
using AutoMapper;
namespace AutoMapperConsoleExample
{
public class CalendarEvent
{
public DateTime Date { get; set; }
public string Title { get; set; }
}
public class CalendarEventForm
{
public DateTime EventDate { get; set; }
public int EventHour { get; set; }
public int EventMinute { get; set; }
public string Title { get; set; }
}
class Student
{
public string Name { get; set; }
public string Email { get; set; }
public Adress Adress { get; set; }
}
class StudentViewModel
{
public string Name { get; set; }
public string Email { get; set; }
public string Adress { get; set; }
}
class Adress
{
public string Country { get; set; }
public string City { get; set; }
}
class Program
{
static void Main(string[] args)
{
var calendarEvent = new CalendarEvent
{
Date = new DateTime(2008, 12, 15, 20, 30, 0),
Title = "Company Holiday Party"
};
var student = new Student
{
Name = "Willams",
Email = "email@email.com",
Adress = new Adress
{
Country = "Brasil",
City = "Americana"
}
};
var configuration = new MapperConfiguration(cfg =>
{
cfg.CreateMap<CalendarEvent, CalendarEventForm>()
.ForMember(dest => dest.EventDate, opt => opt.MapFrom(src => src.Date.Date))
.ForMember(dest => dest.EventHour, opt => opt.MapFrom(src => src.Date.Hour))
.ForMember(dest => dest.EventMinute, opt => opt.MapFrom(src => src.Date.Minute));
cfg.CreateMap<Student, StudentViewModel>()
.ForMember(dest => dest.Adress, opt => opt.MapFrom(src => src.Adress.City + ", " + src.Adress.Country));
});
var mapper = configuration.CreateMapper();
CalendarEventForm form = mapper.Map<CalendarEvent, CalendarEventForm>(calendarEvent);
Console.WriteLine($"{form.EventDate}");
StudentViewModel studentViewModel = mapper.Map<Student, StudentViewModel>(student);
Console.WriteLine($"Name: {studentViewModel.Name}");
Console.WriteLine($"Email: {studentViewModel.Email}");
Console.WriteLine($"Adress: {studentViewModel.Adress}");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment