Skip to content

Instantly share code, notes, and snippets.

@nzhul
Last active August 29, 2015 14:25
Show Gist options
  • Save nzhul/780176e0ac563cded144 to your computer and use it in GitHub Desktop.
Save nzhul/780176e0ac563cded144 to your computer and use it in GitHub Desktop.
This is an simple example of how one can use AutoMapper Library
using Models;
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
namespace Data
{
public class UsersService
{
public ICollection<User> Users { get; set; }
public UsersService()
{
this.Users = new List<User>();
this.Users.Add(new User() { Id = 1, FirstName = "Gosho", LastName = "Ivanov", Age = 11 });
this.Users.Add(new User() { Id = 2, FirstName = "Atanas", LastName = "Georgiev", Country = "Bulgaria" });
this.Users.Add(new User() { Id = 3, FirstName = "Spas", LastName = "Trendafilov" });
}
public IList<UserViewModel> GetUsers()
{
Mapper.CreateMap<User, UserViewModel>()
.ForMember(u => u.FullName, map => map.MapFrom(p => p.FirstName + " " + p.LastName));
IList<UserViewModel> userViewModelCollection = new List<UserViewModel>();
foreach (var currentUser in this.Users)
{
UserViewModel userViewModel = Mapper.Map<User, UserViewModel>(currentUser);
userViewModelCollection.Add(userViewModel);
}
return userViewModelCollection;
}
}
public class User
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Country { get; set; }
public DateTime DateCreated { get; set; }
public int Age { get; set; }
}
public class UserViewModel
{
public int Id { get; set; }
public string FullName { get; set; }
public int Age { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment