C# AutoMapper 了解一下

什么是AutoMapper?

简单来说就是将一个对象映射到另一个对象的代码。 摆脱了繁琐的赋值过程 (最常见也就是Model -——ViewModel)

AutoMapper安装

我使用的是VS2015   可以在NuGet中直接输入AutoMapper 去下载

也可以使用控制台命令

PM> Install-Package AutoMapper

 

这里我定义了两个类   ShopingInfo         ShopingInfoViewModel

public class ShopingInfo:EntityBase
    {
        public string ShopingName { get; set; }

        public int ShopingCount { get; set; }

        public decimal ShopingPric { get; set; }

        public int Stock { get; set; }

        public int Volumeofvolume { get; set; }

        public int ShopingTypeId { get; set; }

        public virtual ShopingType ShopingType { get; set; }
    }
  public class ShopingInfoViewModel
    {
        public int ID { get; set; }
       
        public string ShopingName { get; set; }
      
        public int ShopingCount { get; set; }
        
        public decimal ShopingPric { get; set; }
        
        public int Stock { get; set; }
        
        public int Volumeofvolume { get; set; }
      
        public string ShopingTypeName { get; set; }
    }

 

需要用到的命名空间

using AutoMapper;

 

然后 专门建了一个类用来存放这些映射关系SourceProfile 并且继承了 Profile

   public class SourceProfile : Profile
    {
       public SourceProfile()
        {
            base.CreateMap<ShopingInfo, ShopingInfoViewModel>();
        }
    }

  

如果 我们发现两类中有字段名不一致。 

例如 我吧shopingInfoViewModel 中的 ShopingName  改为  Name    那你可以这样写

public class SourceProfile : Profile
    {
       public SourceProfile()
        {
           base.CreateMap<ShopingInfo, ShopingInfoViewModel>();

          // base.CreateMap<ShopingInfo, ShopingInfoViewModel>().ForMember(x => x.Name,
          //      q => { q.MapFrom(z => z.ShopingName);
          //  });
        }
    }

建了个中间类 用来封装上面的代码

  public class AutoMapper
    {
        public static void Start()
        {
            Mapper.Initialize(x =>
            {
                x.AddProfile<SourceProfile>();
            });
        }
    }

然后就在全局类Global中 使得 启动初始化就去加载 加入下面这句代码

AutoMapper.Start();//好了。 基本的都搞好了。 现在测试一下可以 看到 已经映射上去了。 学习不能停下。 每天学习点。 会使自己变得越有价值

 

posted @ 2019-08-01 13:29  聖潔  阅读(1034)  评论(1编辑  收藏  举报