EF架构~AutoMapper对象映射工具简化了实体赋值的过程

时间:2023-03-09 05:34:10
EF架构~AutoMapper对象映射工具简化了实体赋值的过程

回到目录

AutoMapper是一个.NET的对象映射工具,一般地,我们进行面向服务的开发时,都会涉及到DTO的概念,即数据传输对象,而为了减少系统的负载,一般我们不会把整个表的字段作为传输的数据,而是单独根据具体场景,写一个新的类,这个类一般以DTO结尾,意思是说,它是网络上的数据传输用的,而你的DTO数据对象的赋值过程就成了一个问题,而为了减少赋值过程的代码量,AutoMapper就出来了,它可以实现实体对实体的赋值过程,或者叫“映射过程”

我心中的项目应该是这样的,用户业务服务,产品业务服务,订单业务服务,这样服务都使 用单独的数据库,它们之间的通讯采用WCF进行实现,在获数据时会在WEB端添加缓存机制,以减少对WCF的调用,而在WCF的网络通讯中,数据类型一般 不会使用poco实体,因为它会有很多对当前业务无用的字段,我们会为具体业务建立具体的DTO对象,而entity实体与DTO实体之间的赋值过程我们 可以用AutoMapper来实现。

AutoMapper在程序中的体现:

DTO实体

[DataContract]
public class ProductDTO
{
[DataMember]
public int ProductID { get; set; }
[DataMember]
public string ProductName { get; set; }
[DataMember]
public System.DateTime CreateDate { get; set; }
[DataMember]
public int SaleCount { get; set; }
[DataMember]
public Nullable<int> ClickCount { get; set; }
[DataMember]
public string Info { get; set; }
[DataMember]
public int UserID { get; set; }
[DataMember]
public decimal SalePrice { get; set; }
[DataMember]
public int Discount { get; set; }
}

POCO实体:

 public partial class Product
{
public Product()
{
this.ProductDetail = new HashSet<ProductDetail>();
}
public int ProductID { get; set; }
public string ProductName { get; set; }
public System.DateTime CreateDate { get; set; }
public int SaleCount { get; set; }
public Nullable<int> ClickCount { get; set; }
public string Info { get; set; }
public int UserID { get; set; }
public decimal SalePrice { get; set; }
public int Discount { get; set; }
public System.DateTime UpdateDate { get; set; } public virtual User_Info User_Info { get; set; }
public virtual ICollection<ProductDetail> ProductDetail { get; set; }
}

下面使用AutoMapper实现对象两个实体的赋值,这是WCF服务中的代码片断:

public class ProductService : ServiceBase, IProductService
{ //通过ServiceLocator从IoC容器中获得对象
IProductRepository productRepository = ServiceLocator.Instance.GetService<IProductRepository>(); #region IProductService 成员 public ProductDTO CreateProduct(ProductDTO productDTO)
{
Mapper.CreateMap<ProductDTO, Product>();
Product product = Mapper.Map<ProductDTO, Product>(productDTO);
productRepository.AddProduct(product);
return productDTO;
} public List<ProductDTO> GetProduct()
{
Mapper.CreateMap<Product, ProductDTO>();
List<ProductDTO> arr = new List<ProductDTO>();
productRepository.GetProduct().ForEach(i =>
{
arr.Add(Mapper.Map<Product, ProductDTO>(i));
});
return arr;
} public ProductDTO ModifyProduct(ProductDTO productDTO)
{
Mapper.CreateMap<ProductDTO, Product>();
Product product = Mapper.Map<ProductDTO, Product>(productDTO);
productRepository.ModifyProduct(product);
return productDTO;
} #endregion
}

怎么样,这种方式的对象赋值很爽吧,呵呵。

回到目录