AutoMapper扩展方法

AutoMapper在MVC中的运用-映射中的忽略、处理null、多种映射转换

在项目中通过Nuget添加一个AutoMapper插件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcApplication2.Controllers
{
    using EFModel;
    using EFModel.ModelView;
    using Mapping;
    using EmitMapper;
    using AutoMapper;
    using System.Collections;
    public class HomeController : Controller
    {
        //
        // GET: /Home/


        public ActionResult Index()
        {
            JKCRMEntities db = new JKCRMEntities();

            sysFunction model = db.sysFunction.FirstOrDefault(r => r.fID == 20);

            //进行对象转换(将sysFunction类型的对象实例转换成sysFunctionView类型的对象实例)
            sysFunctionView modelView = AutoMapperExtension.MapTo(model);
 
            return View();
        }


    }

    ///  
    /// AutoMapper扩展方法 
    ///  
    public static class AutoMapperExtension
    {
        ///  
        /// 集合对集合	
        ///  
        ///  
        ///  
        ///  
        public static List MapTo(this IEnumerable self)
        {
            if (self == null) throw new ArgumentNullException();
            Mapper.CreateMap(self.GetType(), typeof(TResult));
            return (List)Mapper.DynamicMap(self, self.GetType(), typeof(List));
        }
        ///  
        /// 对象对对象 
        ///  
        ///  
        ///  
        /// 
        public static TResult MapTo(this object self)
        {
            if (self == null) throw new ArgumentNullException();
            Mapper.CreateMap(self.GetType(), typeof(TResult));
            return (TResult)Mapper.DynamicMap(self, self.GetType(), typeof(TResult));
        }
    }
}


你可能感兴趣的:(EF,Linq,List,泛型)