我有一个用 C# 编写的分层应用程序 -
Front end - (Get pages of
Customers
)Business - (
CustomerService
andCustomer
class)DataContracts - (
CustomerDTO
)DataAccess - (
UnitOfWork
andRepositories
)
数据库有一个包含一百多个列(很多是冗余的)的 Customer 表,所以我使用 DTO 在业务层填充 Customer 对象。在 Customer 类中,我也从数据库名称中更改了许多字段的名称,例如ID 到 CustomerID,FName 到 Firstname。
前端使用业务层的服务来获取客户,例如GetAll(), GetByID(int customerID).
我还想提供如下所示的 GetPaged 方法
。
客户服务类
public IEnumerable<Customer> GetPaged(
Func<IQueryable<Customer>, IOrderedQueryable<Customer>> orderBy,
int skip,
int take)
{
foreach (var customerDTO in
unitOfWork.CustomerRepository.GetPaged(orderBy, skip, take))
{
yield return new Customer(customerDTO);
}
}
但这不会起作用,因为 CustomerRepository
需要一个基于 CustomerDTO
而不是 Customer
的 orderBy
.
我不想让前端知道关于 CustomerDTO
的任何信息。
我怎样才能做到这一点?
最佳答案
您可以公开一个包含可用订单选项的 enum
,然后在 GetPaged
中您只需根据收到的枚举值创建 OrderBy。
可能的实现可能是:
public enum OrderCustomersBy
{
FirstNameAsc, FirstNameDesc, AgeAsc, AgeDesc
}
在客户服务中:
private IOrderedQueryable<CustomerDTO> GetOrderBy(OrderCustomersBy orderOption)
{
IOrderedQueryable<CustomerDTO> orderBy = null;
switch (orderOption)
{
case OrderCustomersBy.FirstNameAsc:
// Create order by...
break;
case OrderCustomersBy.FirstNameDesc:
// Create order by...
break;
case OrderCustomersBy.AgeAsc:
// Create order by...
break;
case OrderCustomersBy.AgeDesc:
// Create order by...
break;
default:
throw new NotImplementedException("Order option not implemented: " + orderOption.ToString());
}
return orderBy;
}
public IEnumerable<Customer> GetPaged(Func<IQueryable<Customer>> func, OrderCustomersBy orderOption, int skip, int take)
{
IOrderedQueryable<CustomerDTO> orderBy = this.GetOrderBy(orderOption);
foreach (var customerDTO in unitOfWork.CustomerRepository.GetPaged(orderBy, skip, take))
{
yield return new Customer(customerDTO);
}
}
关于c# - 在 N 层应用程序中使用 DTO 时的 OrderBy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14988357/