Barış Kısır

Software Developer

Navigation
 » Home
 » Resume
 » Projects
 » Contact
 » RSS

Automapper usage in .NET

29 Apr 2017 » csharp

How do you handle with DAL objects and ViewModel objects?

Are you still writing mapper for every class?

I guess you’re wasting your time…

Meet Automapper! A convention-based object-object mapper.

Installation with NuGet

Install-Package AutoMapper


ViewModel

class UserViewModel
{
    public string Name { get; set; }
    public string Surname { get; set; }
    public string EmailAddress { get; set; }
}

DAL Object

class User
{
    public User()
    {
    this.Id = Guid.NewGuid();
    this.CreateDate = DateTime.Now;
    }
public Guid Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string EmailAddress { get; set; }
public DateTime CreateDate { get; set; }
}

Automapping

// Initialize AutoMapper
AutoMapper.Mapper.Initialize(x => x.CreateMap<UserViewModel, User>());
// Single Object
UserViewModel userViewModel = new UserViewModel();
userViewModel.Name = "Kemal";
userViewModel.Surname = "Etikan";
userViewModel.EmailAddress = "kemaletikan@example.com";
// Mapping single object
User user = AutoMapper.Mapper.Map<UserViewModel, User>(userViewModel);
//Mapping list with custom object
List<UserViewModel> userViewModelList = new List<UserViewModel>();
userViewModelList.Add(userViewModel);
List<User> userList = AutoMapper.Mapper.Map<List<UserViewModel>, List<User>>(userViewModelList);

You can download source code from –> Here

automapper-single