当前位置: 首页 > 工具软件 > Automapper.js > 使用案例 >

AutoMapper扩展方法

陆烨磊
2023-12-01

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<sysFunctionView>(model);
 
            return View();
        }


    }

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


 类似资料: