美文网首页
试试automapper

试试automapper

作者: 小狼在IT | 来源:发表于2018-04-29 11:52 被阅读0次

    用nuget安装AutoMapper。
    如果熟悉相同,可以直接mapper;如果不同,就需要定义下mapper规则,这里先展示个简单的用法。

    一些类:

     public class Book
    {
        public string Title { get; set; }
        public Author Author { get; set; }
        public Prd product { get; set; }
    }
    public class BookViewModel
    {
        public string Title { get; set; }
        public string Author { get; set; }
        public string ItemNo { get; set; }
    }
    public class Author
    {
        public string Name { get; set; }
    }
    public class Prd
    {
        public string itemNo { get; set; }
        public string model { get; set; }
    }
    

    使用:

        static void Main(string[] args)
        {
            //方式1:
            var a = new AutoMapper.Configuration.MapperConfigurationExpression();
    
            a.CreateMap<Book, Author>().ForMember(dest => dest.Name,
                opts => opts.MapFrom(src => src.Author.Name));
    
            a.CreateMap<Book, BookViewModel>().ForMember(dest => dest.ItemNo,
               opts => opts.MapFrom(src => src.product.itemNo))
                .ForMember(dest => dest.Author,
                opts => opts.MapFrom(src => src.Author.Name));
    
            AutoMapper.Mapper.Initialize(a);
    
            //方式2:
            //AutoMapper.Mapper.Initialize(c => {
            //    c.CreateMap<Book, BookViewModel>().ForMember(dest => dest.Author,
            //    opts => opts.MapFrom(src => src.Author.Name));
    
            //    c.CreateMap<Book, Author>().ForMember(dest => dest.Name,
            //    opts => opts.MapFrom(src => src.Author.Name));
            //});
    
            Book b1 = new Book();
            b1.Title = "题目";
            b1.Author = new Author();
            b1.Author.Name = "作者";
            b1.product = new Prd();
            b1.product.itemNo = "12001";
            b1.product.model = "a3001";
    
            BookViewModel bvm = AutoMapper.Mapper.Map<BookViewModel>(b1);
            Console.WriteLine(JsonHelper.ToJson(bvm));
    
            Author author = AutoMapper.Mapper.Map<Author>(b1);
            Console.WriteLine(JsonHelper.ToJson(author));
    
            Console.ReadKey();
        }
    

    结果:


    image.png

    相关文章

      网友评论

          本文标题:试试automapper

          本文链接:https://www.haomeiwen.com/subject/onuolftx.html