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));
        }

    }

回到目錄


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM