• ASP.NET.Core中使用AutoMapper


     

      首先需要在NuGet中引用AutoMapper的类库

    install-package   AutoMapper
    install-package   AutoMapper.Extensions.Microsoft.DependencyInjection

    然后创建好要进行转换的类

    public class User
    {
            public int ID { get; set; }
            public string Name { get; set; }
    }
    public class UserDto
    {
            public int ID { get; set; }
            public string Name { get; set; }
    }

      然后再创建一个标志接口IProfile

    internal interface IProfile
        {
        }

       接下来创建一个类来继承AutoMapper的Profile类与实现刚才创建的标志接口IProfile,并且在构造函数中配置关系映射

     public class MyProfile: Profile,IProfile
        {
            public MyProfile()
            {
                CreateMap<User, UserDto>();
                CreateMap<UserDto, User>();
            }
           
        }

      然后再创建一个类来注册关系映射

    public class Mappings
        {
            public static void RegisterMappings()
            {
                //获取所有IProfile实现类
                var allType =
                Assembly
                   .GetEntryAssembly()//获取默认程序集
                   .GetReferencedAssemblies()//获取所有引用程序集
                   .Select(Assembly.Load)
                   .SelectMany(y => y.DefinedTypes)
                   .Where(type => typeof(IProfile).GetTypeInfo().IsAssignableFrom(type.AsType()));
    
                foreach (var typeInfo in allType)
                {
                    var type = typeInfo.AsType();
                    if (type.Equals(typeof(IProfile)))
                    {
                        //注册映射
                        Mapper.Initialize(y =>
                        {
                            y.AddProfiles(type); // Initialise each Profile classe
                        });
                    }
                }
            }
    
        }

     从上面代码可以看出使用标志接口来判断注册映射类进行注册映射,

     最后只需在Startup类的ConfigureServices方法中添加服务和将Mappings添加到中间件即可使用

     public void ConfigureServices(IServiceCollection services)
            {
                services.AddAutoMapper();
                services.AddMvc();
                
            }
     public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                Mappings.RegisterMappings();
            }

     然后就可以使用automapper,

    public class ValuesController : Controller
        {
            
            private IMapper _mapper { get; set; }
            public ValuesController([FromServices]IMapper mapper)
            {
                this._mapper = mapper;
            }
    
            // GET api/values
            [HttpGet]
            public UserDto Get()
            {
                User user = new User()
                {
                    ID = 1,
                    Name = "狗娃"
                };
                var dto = Mapper.Map<User, UserDto>(user);
                return dto;
            }
    }

      因为core使用DI创建对象,所以只需添加构造函数即可。

  • 相关阅读:
    UE4物理笔记
    lambda+mutable配合move实现单函数多程序域
    UE导航系统详
    cpp智能指针
    [转载]新手应该如何学习网站分析
    webpack 单独打包指定JS文件
    vue-cli axios ie9 问题
    [分享] 通过修改CSS自定义chrome滚动条样式
    日期格式化转换方法
    vue 路劲
  • 原文地址:https://www.cnblogs.com/yan7/p/8085410.html
Copyright © 2020-2023  润新知