(精华)2020年9月21日 ASP.NET Core AutoMapper的使用

举报
愚公搬代码 发表于 2021/10/19 01:13:22 2021/10/19
【摘要】 没有AutoMapper需要一个一个赋值 public class Sample01 { public static void Run() { var result = ...

没有AutoMapper需要一个一个赋值

public class Sample01
{
    public static void Run()
    {
        var result = GetStudents();

        var students = new List<StudentViewModel>();

        foreach (var item in result)
        {
            var student = new StudentViewModel
            {
                Id = item.Id,
                Age = item.Age,
                Name = item.Name,
                Gender = item.Gender
            };
            students.Add(student);
        }
        Print(students);
    }

    public static List<Student> GetStudents()
    {
        var context = new SampleContext();
        return context.Students;
    }

    public static void Print(IList<StudentViewModel> studentViewModels)
    {
        foreach (var student in studentViewModels)
        {
            Console.WriteLine($"Id={student.Id};Name={student.Name};");
        }
    }
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36

AutoMapper配置映射

public class Sample02
    {
        public static void Run()
        {
            
            var config = new MapperConfiguration(cfg => cfg.CreateMap<Student, StudentViewModel>());
            var mapper = config.CreateMapper();

            var result = GetStudents();
            var students = mapper.Map<List<StudentViewModel>>(result);
            Print(students);
        }

        public static List<Student> GetStudents()
        {
            var context = new SampleContext();
            return context.Students;
        }

        public static void Print(IList<StudentViewModel> studentViewModels)
        {
            foreach (var student in studentViewModels)
            {
                Console.WriteLine($"Id={student.Id};Name={student.Name};Age={student.Age};Gender={student.Gender}");
            }
        }
    }

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

AutoMapper 扁平化映射

public static void Run()
{
    var config = new MapperConfiguration(cfg =>
    {
        cfg.CreateMap<User, UserViewModel>()
            .ForMember(
                model => model.City,
                expression => expression.MapFrom(user => user.Address.City))
            .ForMember(
                model => model.Country,
                expression => expression.MapFrom(user => user.Address.Country))
            .ForMember(
                model => model.State,
                expression => expression.MapFrom(user => user.Address.State));
    });
    var mapper = config.CreateMapper();

    var result = GetUsers();
    var users = mapper.Map<List<UserViewModel>>(result);
    Print(users);
}

public static List<User> GetUsers()
{
    var context = new SampleContext();
    return context.Users;
}

public static void Print(IList<UserViewModel> userViewModels)
{
    foreach (var user in userViewModels)
    {
        Console.WriteLine($"Id={user.Id};Name={user.Name};City={user.City}");
    }
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35

Profile

public class StudentProfile : Profile
{
    public StudentProfile()
    {
        CreateMap<Student, StudentViewModel>();
    }
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
public class UserProfile : Profile
{
    public UserProfile()
    {
        CreateMap<User, UserViewModel>()
            .ForMember(
                model => model.City,
                expression => expression.MapFrom(user => user.Address.City))
            .ForMember(
                model => model.State,
                expression => expression.MapFrom(user => user.Address.State))
            .ForMember(
                model => model.Country,
                expression => expression.MapFrom(user => user.Address.Country));

    }
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
public class Sample04
{
    public static void Run()
    {
        
        var config = new MapperConfiguration(cfg =>
        {
            cfg.AddProfile<UserProfile>();
            cfg.AddProfile<StudentProfile>();
        });

        var mapper = config.CreateMapper();

        var result = GetUsers();
        var users = mapper.Map<List<UserViewModel>>(result);
        Print(users);
    }

    public static List<User> GetUsers()
    {
        var context = new SampleContext();
        return context.Users;
    }

    public static void Print(IList<UserViewModel> userViewModels)
    {
        foreach (var user in userViewModels)
        {
            Console.WriteLine($"Id={user.Id};Name={user.Name};City={user.City}");
        }
    }
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

AutoMapper 自定义解析

public class Customer
{
    public int Id { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
public class CustomerViewModel
{
    public int Id { get; set; }

    public string FullName { get; set; }
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
public class CustomerResolver : IValueResolver<Customer, CustomerViewModel, string>
{
    public string Resolve(Customer source, CustomerViewModel destination, string destMember, ResolutionContext context)
    {
        return source.FirstName + " " + source.LastName;
    }
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
public static void Run()
{
    var config = new MapperConfiguration(cfg =>
    {
        cfg.CreateMap<Customer, CustomerViewModel>()
            .ForMember(model => model.FullName, expression => expression.MapFrom<CustomerResolver>());
    });

    var mapper = config.CreateMapper();

    var customer = new Customer
    {
        Id = 1,
        FirstName = "Klein",
        LastName = "Moretti"
    };

    var result = mapper.Map<CustomerViewModel>(customer);
    Console.WriteLine(result.FullName);
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

AutoMapper 自定义类型转换

public class Person
{
    public int Id { get; set; }

    public string Name { get; set; }

    public int Age { get; set; }
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
public class PersonViewModel
{
    public int Id { get; set; }

    public string Name { get; set; }

    public string Age { get; set; }
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
 public class StringTypeConverter : ITypeConverter<int, string>
{

    public string Convert(int source, string destination, ResolutionContext context)
    {
        return source.ToString();
    }
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
public static void Run()
{
    var config = new MapperConfiguration(cfg =>
    {
        cfg.CreateMap<int, string>().ConvertUsing<StringTypeConverter>();
        cfg.CreateMap<Person, PersonViewModel>();
    });

    var mapper = config.CreateMapper();

    var person = new Person
    {
        Id = 1,
        Age = 10
    };

    var result = mapper.Map<PersonViewModel>(person);
    Console.WriteLine($"{result.Age.GetType()}:Age={result.Age})");
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

AutoMapper 动态对象映射

public static void Run()
{
    var config = new MapperConfiguration(cfg => {});
    var mapper = config.CreateMapper();

    var customer = new Customer
    {
        Id = 1,
        FirstName = "Klein",
        LastName = "Moretti"
    };

    // 强类型对象映射到动态类型对象
    var result = mapper.Map<dynamic>(customer);
    Console.WriteLine($"result:{result.FirstName} {result.LastName}");

    // 动态类型对象映射到强类型对象
    customer = mapper.Map<Customer>(result);
    Console.WriteLine($"customer:{customer.FirstName} {customer.LastName}");

    // 字典对象映射到强类型对象
    var dict = new Dictionary<string, object> {{"FirstName", "Klein"}, {"LastName", "Moretti"}};
    customer = mapper.Map<Customer>(dict);
    Console.WriteLine($"dictToCustomer:{customer.FirstName} {customer.LastName}");
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

AutoMapper在ASP.NET Core中使用

首先安装如下两个包

AutoMapper
AutoMapper.Extensions.Microsoft.DependencyInjection

  
 
  • 1
  • 2
public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();

        services.AddSingleton<SampleContext>();
        services.AddScoped<OrderRepository>();

        services.AddAutoMapper(Assembly.GetExecutingAssembly());

        services.AddMediatR(Assembly.GetExecutingAssembly());
        
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
public class OrderProfile : Profile
    {
        public OrderProfile()
        {
            CreateMap<Order, GetOrderByIdResponseModel>();
        }
    }

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
public class GetOrderByIdResponseModel
    {
        public Guid Id { get; set; }
        public DateTime DateOrder { get; set; }
        public int Quantity { get; set; }
        public double Amount { get; set; }
        public Guid ProductId { get; set; }
        public string ProductName { get; set; }
    }

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
public class GetOrderByIdQueryHandler : IRequestHandler<GetOrderByIdRequestModel, GetOrderByIdResponseModel>
{
    private readonly OrderRepository _orderRepository;
    private readonly IMapper _mapper;

    public GetOrderByIdQueryHandler(OrderRepository orderRepository, IMapper mapper)
    {
        _orderRepository = orderRepository;
        _mapper = mapper;
    }

    public Task<GetOrderByIdResponseModel> Handle(GetOrderByIdRequestModel request, CancellationToken cancellationToken)
    {
        var order = _orderRepository.GetById(request.OrderId);
        var response = _mapper.Map<GetOrderByIdResponseModel>(order);
        return Task.FromResult(response);
    }
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
[Route("api/[controller]")]
[ApiController]
public class OrderController : ControllerBase
{
    private readonly IMediator _mediator;

    public OrderController(IMediator mediator)
    {
        _mediator = mediator;
    }

    [HttpPost]
    public IActionResult MakeOrder([FromBody] MakeOrderRequestModel requestModel)
    {
        var response = _mediator.Send(requestModel).Result;
        return Ok(response);
    }

    [HttpGet("{id}")]
    public IActionResult OrderDetails(Guid id)
    {
        var response = _mediator.Send(new GetOrderByIdRequestModel {OrderId = id}).Result;
        return Ok(response);
    }
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

文章来源: codeboy.blog.csdn.net,作者:愚公搬代码,版权归原作者所有,如需转载,请联系作者。

原文链接:codeboy.blog.csdn.net/article/details/108524490

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。