首页 > 移动平台 > 详细

.Net Mvc AutoMapper简单使用

时间:2017-05-15 19:01:12      阅读:614      评论:0      收藏:0      [点我收藏+]

1、安装automapper nuget包。

技术分享

2、新建一个AutoMapper配置类并实现一个静态配置方法。

using AutoMapper;
using AutoMapperTest.Models;

namespace AutoMapperTest.App_Start
{
    public class AutoMapperConfig
    {
        public static void Config()
        {
            Mapper.Initialize(cfg =>
            {
                cfg.CreateMap<StudentEntity, StudentOutput>();
            });
        }
    }
}

3、在全局配置Global.asax中引用配置方法。

using AutoMapperTest.App_Start;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace AutoMapperTest
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AutoMapperConfig.Config();
        }
    }
}

4、具体使用

        public JsonResult GetMapper()
        {
            //实例化实体List
            List<StudentEntity> StudentList = new List<StudentEntity>();
            //模拟数据
            StudentList.Add(new StudentEntity
            {
                Id = 1,
                Age = 12,
                Gander = "boy",
                Name = "WangZeLing",
                Say = "Only the paranoid survive",
                Score = 99M
            });
            //AuotMapper具体使用方法 将List<StudentOutput>转换为List<StudentOutput>
            List<StudentOutput> Output = AutoMapper.Mapper.Map<List<StudentOutput>>(StudentList);
            return Json(Output, JsonRequestBehavior.AllowGet);
        }

附:实体类、Output类

    public class StudentEntity
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public string Gander { get; set; }
        public decimal Score { get; set; }
        public string Say { get; set; }
    }
    public class StudentOutput
    {
        public string Name { get; set; }
        public decimal Score { get; set; }
        public string Say { get; set; }
    }

附:AutoMapper GitHub 

https://github.com/AutoMapper/AutoMapper

 

.Net Mvc AutoMapper简单使用

原文:http://www.cnblogs.com/eedc/p/6857742.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!