【发布时间】:2017-07-02 21:10:29
【问题描述】:
我希望能得到一点帮助...
假设在一个应用程序中,我们有一个数据层和一个业务逻辑层。在 DAL 中,我们有以下实体:
public class Customer {
public string Name {get; set;}
public ICollection<Address> Addresses {get; set;}
}
public class Address {
public string Street {get; set;}
}
在 BLL 中,我们有以下 POCO:
public class CustomerDto {
public string Name {get; set;}
public ICollection<AddressDto> Addresses {get; set;}
}
public class AddressDto {
public string Street {get; set;}
}
DAL 中的实体使用轻量级 ORM 填充,并使用存储库从 BLL 中检索。例如:
public class CustomerInformationService {
private readonly ICustomerRepository _repository {get; set;}
public CustomerInformationService (ICustomerRepository repository)
{
_repository = repository;
}
public class CustomerDto Get(int id)
{
var customerEntity = _repository.Get(id);
var customerDto = /* SOME TRANSFORMATION HERE */
return customerDTO;
}
}
我的问题是关于 /* SOME TRANSFORMATION HERE */ 部分。我们团队中有一个关于如何进行“映射”的讨论。
一种方法是使用自动映射器或手动映射器。 第二种方法是使用类似于 Entity 的包装器并引用 DTO 以保存对象之间的复制操作。像这样的:
public class CustomerDto
{
private IEntity _customerEntity;
public IEntity CustomerEntity { get {return _customerEntity;}}
public CustomerDto(IEntity customerEntity)
{
_customerEntity = customerEntity;
}
public string Name
{
get { return _customerEntity.Name; }
}
public ICollection<Address> Addresses
{
get { return _customerEntity.Addresses; }
}
}
第二种方法对我来说有点奇怪,因为 _customerEntity.Addresses 感觉就像我的 DAL 和我的 BLL 之间的泄漏(_customerEntity 的引用),但我不确定。
使用一种方法比另一种方法有什么优点/缺点吗?
附加信息:我们通常会拉一个最大值。一次需要在 Entity 和 DTO 之间转换的 1000 条记录。
【问题讨论】:
-
如果您打算使用包装器方法,您不妨只使用实体而忘记使用 dto 对象。您没有购买任何使用包装器的东西,而是添加了紧密耦合和另一个依赖项。
-
@dbugger - 谢谢你的回答。你是指哪个依赖?无论我们使用映射器还是包装器来创建 DTO,BLL 都会始终知道来自 DAL 的接口。
标签: oop automapper data-access-layer objectmapper