AutoMapperサンプルコード

sample

github.com

kiyokura.hateblo.jp

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;

namespace AutoMapperTest
{
    public class Book
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public int Price { get; set; }
        public int AuthorId { get; set; }
        public List<int> IntList { get; set; }
    }

    public class BookViewModel
    {
        public string Title { get; set; }
        public int Price { get; set; }
        public string AuthorName { get; set; }
        public List<int> IntList { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Book book = new Book
            {
                Title = "title",
                Price = 1000,
                IntList = new List<int>(Enumerable.Range(1, 10))
            };

            Mapper.Initialize(cfg => { cfg.CreateMap<Book, BookViewModel>(); });
            BookViewModel bvm = Mapper.Map<BookViewModel>(book);
            Console.WriteLine(bvm.Title);
            Console.WriteLine(bvm.Price);
            Console.WriteLine(bvm.IntList.Sum());


            Console.WriteLine("press any key to exit...");
            Console.ReadLine();
        }
    }
}