AutoMapper 通过 Profile来 配置 Mapper

85 篇文章 0 订阅

一般的mapper:

使用AutoMapper转化:

//首先需要先为DTO与Model之间定义一个映射关系

Mapper.CreateMap<DTO, Model>();

DTO dtoData = GetdtoDataFromDB();

Model modelData = Mapper.Map<DTO, Model>(dtoData );

这里的DTO对象就被AutoMapper自动转化成了Model对象,所以modelData中的userName、age、job的值即为GetdtoDataFromDB()方法取出来的值。

实际项目中会通过 Profile来 配置 Mapper:

using AutoMapper;
using System;

namespace AutoMapper_Demo
{
    class Program
    {
        private static IMapper _mapper;
        public class Model
        {
            public class Product
            {
                public string Name { get; set; }
                public decimal Amount { get; set; }
            }
        }
        public class ModelDto
        {
            public class ProductDto
            {
                public string Name { get; set; }
                public decimal Amount { get; set; }
            }
        }



        public class MyProfile
        {
            // 通过automapper的profile来配置mapper
            public class ProductProfile : Profile
            {
                public ProductProfile()
                {
                    CreateMap<Model.Product, ModelDto.ProductDto>();
                }
            }
        }




        static void Main(string[] args)
        {
            var configuration = new MapperConfiguration(cfg =>
            {
                // 以下2中方式都可以
                cfg.AddProfile(new MyProfile.ProductProfile());
                // cfg.AddProfile<MyProfile.ProductProfile>();          
            });

            _mapper = configuration.CreateMapper();

            demo1();
        }


        public static void demo1()
        {
            var proDto = _mapper.Map<ModelDto.ProductDto>(new Model.Product() 
            { 
                Name = "产品一", Amount = 99 
            });

            var result = Newtonsoft.Json.JsonConvert.SerializeObject(proDto);


            Console.WriteLine(result);
            Console.ReadKey();
        }

    }
}

2022/6/30

破案了

我寻思我ABP里面只写了一个Profile文件,看了看项目里也没有一个配置文件可以添加,那我的mapper是咋用的。。。

namespace UIH.Rt.Emr.HRuiJin.HRuijin.ThirdPartReports.MapProfile
{
    internal class ThirdPartReportsMapProfile : Profile
    {
        public ThirdPartReportsMapProfile()
        {
            CreateMap<ThirdPartReportsEntity, ThirdPartReportsDto>();
        }
    }
}

问了问大佬,class继承了Profile接口之后,ABP框架会帮你自动注入。

public abstract class Profile : IProfileExpression, IProfileConfiguration
    {
        //....
    }

新的问题:

 不知道这个配置所有的基本属性和约定,这个该怎么理解。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

董厂长

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值