zoukankan      html  css  js  c++  java
  • EF架构~对AutoMapper实体映射的扩展

    回到目录

    AutoMapper在之前我曾经介绍过,今天主要是把它作一下扩展,因为它的调用太麻烦了,呵呵,扩展之后,用着还可以,感觉.net3.5之后,有了扩展方法这个东西,在程序开发速度及表现力上都有了明显的提升,呵呵。

    当扩展方法开发完之后的效果如下

    实体对实体的映射(赋值)

            var user = new User
                {
                    ID = 1,
                    Name = "zzl",
                    CreateDate = DateTime.Now,
                };
           UserModel model = user.MapTo<UserModel>();
            Console.WriteLine(model.ID + model.Name);

    集合对集合的映射(赋值)

           var userList = new List<User> { user };
                userList.Add(new User
                {
                    ID = 2,
                    Name = "zzllr",
                    CreateDate = DateTime.Now,
                });
                var modelList = userList.MapTo<UserModel>();
                modelList.ForEach(i =>
                {
                    Console.WriteLine(i.Name);
                });

    下面是扩展方法的代码,一个是实体的,一个是集合的

       /// <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.Map(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.Map(self, self.GetType(), typeof(TResult));
            }
    
        }

    回到目录

  • 相关阅读:
    Codeforces977D ---Divide by three, multiply by two 深搜+map存出现的数
    HDU4522 湫湫系列故事——过年回家
    2018浙江省赛记录
    POJ3259 :Wormholes(SPFA判负环)
    上海高校金马五校赛 F题:1 + 2 = 3?
    牛客练习赛15A-吉姆的运算式(Python正则表达式瞎搞)
    ZOJ2018/4月月赛G题Traffic Light(广搜)
    luogu 3960 列队
    noip2017
    10.3 模拟赛
  • 原文地址:https://www.cnblogs.com/lori/p/3327898.html
Copyright © 2011-2022 走看看