一般的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
{
//....
}
新的问题:
不知道这个配置所有的基本属性和约定,这个该怎么理解。