AutoMapper对象转换方面(Object-Object Mapping)对象映射工具,实现对象和对象之间的转化。主要应用在项目的dto,model,entity或viewmodel之间转换,其实AutoMapper涵盖所有对象(Object)之间的转换。
下面演示他的基本用法:
public class Customer
{
public Guid Id { get; set; } public string Number { get; set; }
public string Name { get; set; }
public DateTime RegDate { get; set; }
public string Note { get; set; }
public string Address { get; set; } public string CategoryID { get; set; }
} public class Product
{
public string Id { get; set; }
public string Number { get; set; }
public string Name { get; set; }
public decimal Price { get; set; } }
public class Order
{
public Customer Customer { get; set; }
public Product Product { get; set; }
public decimal Qty { get; set; } public decimal Getamount()
{
return Product.Price*Qty;
}
}
先建立这几个类,order、customer、product显示订单业务,这些放到领域层。在前台表现层时,可能不需要order类这么复杂,只要orderDto这个简单的类就行了。
public class OrderDto
{
public string CustomerName { get; set; }
public string Address { get; set; }
public decimal Amount { get; set; }
}
这就需要把order的数据转到orderdto对象中。使用automapper进行转换代码如下
public void Test()
{
//先建立实例化对象
Customer _customer = new Customer()
{
Id = new Guid("E8C1D91F-7076-489B-BAA8-8F563BA07402"),
Number = "01.001",
Name = "明康医院",
RegDate = DateTime.Now,
Note = "sadfasdfsdafsdaf",
Address = "XX省sss市CCC路32号门诊楼对面",
CategoryID = ""
};
Product _product = new Product() {Id = "", Name = "中国式局大全", Number = "", Price = 65.8m}; Order _odr = new Order(){ Customer = _customer,Product = _product,Qty = 6765m}; // 配置 AutoMapper
Mapper.CreateMap<Order,OrderDto>()
.ForMember(dest => dest.CustomerName, opt => opt.MapFrom(src => src.Customer.Name))//定义映射规则
.ForMember(dest => dest.Address, opt => opt.MapFrom(src => src.Customer.Address))//定义映射规则
.ForMember(dest => dest.Amount, opt => opt.MapFrom(src => src.Getamount()));//定义映射规则 // 执行 mapping
OrderDto form = Mapper.Map<Order, OrderDto>(_odr); Console.WriteLine("客户名称:"+form.CustomerName);
Console.WriteLine("客户地址:" + form.Address);
Console.WriteLine("总金额:" + form.Amount); }
使用automapper先建立映射关系,在执行映射。